I’m learning EF4.1 against the northwind database. I have created a POCO class like this intentionally with non-identical column names and properties that don’t exist in the scheme so I can learn mapping in preparation for updating my legacy app:
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public Decimal? UnitPrice { get; set; }
public bool Discontinued { get; set; }
public Int16 QuantityInStock { get; set; }
public int CategoryID { get; set; }
public Category Category { get; set; }
}
I want to map my schema to this entity like this:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>().Map(config =>
{
config.Properties(p => new
{
p.ProductName,
p.ProductID,
p.CategoryID,
p.Discontinued,
p.UnitPrice
});
});
modelBuilder.Entity<Product>().ToTable("Products");
base.OnModelCreating(modelBuilder);
}
Strangely, when I try this:
Product tmp = db.Products.Find(4);
I get this exception and I can’t tell why since I’m referring to and I even mapped it ToTable(“Products”):
{"Invalid object name 'dbo.Product1'."}
Why is this happening?
With
modelBuilder.Entity<Product>().Mapyou are using a quite advanced mapping option in Code-First called Table Splitting. Your mapping says that the properties of your entityProductyou have listed inProperties(p => new...)should be mapped to another table than the rest of the properties. The rest of the properties is in tableProductsas you have defined in yourToTablecall. For the other properties you don’t have specified a table name at all (which should beToTablewithin theMap(config => config.ToTable(...) ...action). My guess is that EF assumes some kind of default table nameProduct1which apparently doesn’t exist.I’m not sure if you really want to split your entity to two different tables. Reading your first sentences…
… I think you need mainly the following two mapping options:
Properties in the model class without corresponding columns in the database are not mapped properties:
With data annotations:
And you can map a property name to another column name by:
With data annotations: