0

I'm using Entity Framework to insert data into 2 different databases. There are a few columns that are present in one of the databases but not the other. Their data types are not nullable (int and float).

I don't use these columns (when they are present) in my code. Meaning I only insert 0 as the data for them but I can't send null obviously.

Is there a way for me to insert data with ease without creating 2 different versions of my app for these? Ideally I'd like to just have one model with something like an attribute that says insert 0 in this column if it's available.

2 Answers 2

1

If your application runs only against one database, then you can just use an IF statement in your OnModelCreating that uses the Fluent API to .Ignore() the missing properties.

public class MyDbContextWithMissingColumns: MyDbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        if (myConfig.UseDatabaseWithoutSomeProperties)
        {
          modelBuilder.Entity<Foo>().Ignore(f => f.SomeProperty);
        }
        base.OnModelCreating(modelBuilder);
    }
}

If a single instance of your application connects to both databases, then you have to use separate DbContext subtype, as OnModelCreating only runs for the first instance of a DbContext type in an AppDomain.

EG:

public class MyDbContextWithMissingColumns: MyDbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Foo>().Ignore(f => f.SomeProperty);
        base.OnModelCreating(modelBuilder);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

This seems to be exactly what I'm looking for. However it seems that my best option is to have an if statement to use the Ignore() whenever I'm using the 2nd database.
If you never have a single instance of your application that connects to both databases, then an IF statement in OnModelCreating will work. But OnModelCreating only runs for the first instance of a DbContext type in an AppDomain. See updated answer.
0

In the repository for the database with the restricted fields create the entity:

public class MyClass
{
   int MyCommonClassID {get; set;}
   string Name {get; set;}
   [NotMapped]
   string PhoneNumber {get; set;}
}

Where the attribute [NotMapped]. is used that field will not appear in the database but you can use it everywhere else. That wat you determine what gets written at the lowest level and your application doesn't care.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.