If I don't explicitly map a column in code-first EF to an existing DB, will that column still work?
I have the following mapping defined:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<InsuranceProvider>()
.Map(ins => ins.Properties(p => new
{
PKID_Insuance = p.Id,
InsuranceProvider = p.Name,
Address1 = p.Address.Address1,
Address2 = p.Address.Address2,
City = p.Address.City,
State = p.Address.State,
Zipcode = p.Address.Zipcode,
})).ToTable("Insurance");
}
The table and object both share properties such as Phone and Fax with the same name. Do I need to explicitly map those or will the fall into place magically?
Thanks.
Solution:
Sure enough the mapping I proposed did not work. Once I had it working with the .HasColumnName() method, I swapped that out for the code here and got a "the property expression.... is not valid" error. Bummer.
The scaffold "Create" in MVC 3 did, however, pull both the values I defined in the mapping as well as the ones from the Database with the shared names. Fu开发者_JAVA技巧nny how that works.
It would be nice if they brought that syntax back. It seems so much cleaner for remapping large quantities of columns.
Did this work at all what you have so far? The usual way to map properties to column names in the DB is:
modelBuilder.Entity<InsuranceProvider>()
.Property(i => i.Name)
.HasColumnName("InsuranceProvider");
modelBuilder.Entity<InsuranceProvider>()
.Property(i => i.Address.Address1)
.HasColumnName("Address1");
// assuming here that Address is a complex property, not a navigation property
// etc.
And then yes, you don't need to define a mapping for properties which have the same name as the columns in the database. This mapping will happen by convention.
Alternatively you can use the [Column("...")]
attribute on the properties in your model classes (doesn't work though for complex properties, only for scalars, I think).
It will not work. The mapping is not correct. It will create two tables because Map
is used to work with inheritance mapping and entity splitting (as pointed by @Slauma in comment) so your mentioned properties will be in Insurance
table and other properties + PK will be in another table.
Also your usage of Map
is not correct. You must use anonymous type without specifying names of properties.
You must use approach mentioned by @Slauma.
精彩评论