I'm new to C# and EntityFramework and I need to maintain an active software.
I needed to create a new table so I created it in the database and then updated my Model with EntityFramework.
Howewer, it looks like the previous developer had been writing code directly in generated code (The Mode.Context.cs class) and EntityFramework when updating the model is wiping it and rewritting it completly.
So I did a new partial class Model. It looks like this :
public partial class Model : DbContext, IModel
{
public void SomeRandomMethod();
}
And the generated Model looks like this :
public partial class Model : DbContext
{
public Model()
: base("name=Model")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<RandomTable> ARandomTable { get; set; }
}
The problem, however, is that previously, the model was using IDbSet instead of DbSet and the interface IModel is asking for IDbSet<RandomTable> ARandomTable
What would be the proper way to deal with that ?
Normally the
Dbcontextthat represents your database has severalDbSet<TEntity>properties, where everyDbSetrepresents a table in your database.All non-virtual properties of
TEntityrepresent the columns in your table; the virtual properties ofTEntityrepresent the relations between tables: one-to-many, many-to-many etc.Every
DbSet<TEntity>implementsIDbSet<TEntity>so wherever your oldDbContextused anIDbSet, you can give it the correspondingDbSetinstead.If I understand you correctly, your old
DbContexthad some properties that implementedIDbSet<...>, and methodSomeRandomMethodused these properties.Now your new DbContext. If the DbSets have the same Entity types as the old ones, there is no problem:
Note that AEntities/BEntities are now
DbSet<...>instead ofIDbSet<...>. Because everyDbSet<...>implementsIDbSet<...>, your problem is solved.It is a bit more difficult if your new tables are different than your old ones. In that case you'll have to write adapter properties, that return the expected
IDbSet<...>