I am facing an issue regarding EF code first version while mapping one entity to multiple tables in existing database.
Table1: (primaryKey is IdDocument)
----------------------------
IdDocument | CreationDate
----------------------------
Table 2: (primaryKey is on IdDocument and StartDate)
------------------------------------------------------------
IdDocument | StartDate | Label | LastUpdate
------------------------------------------------------------
In single entity, i was trying to update the information in database. Following is the entity classes.
public abstract class DocumentBase
{
[Column("idDocument")]
public int? IdDocument { get; set; }
[Column("CreationDate")]
public DateTime CreationDate { get; set; }
}
public class Document : DocumentBase
{
[Column("startDate")]
public DateTime StartDate { get; set; }
[Column("lastUpdate")]
public DateTime LastUpdate { get; set; }
[Column("label")]
public string Label { get; set; }
}
Following is the DbModelBuilder for the same entity,
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Document>()
.Map(m =>
{
m.Properties(document => new
{
document.IdDocument,
document.CreationDate
});
m.ToTable("MetaDocument");
}).Map(m =>
{
m.Properties(document => new
{
document.IdDocument,
document.StartDate,
document.EndDate,
document.Label,
document.LastUpdate,
document.Currency
});
m.ToTable("Document");
}).HasKey(key => new
{
key.IdDocument, key.StartDate
});
base.OnModelCreating(modelBuilder);
}
It was failing to update the Table1.
It is not possible to map inheritance if they don’t have same primary key in all tables. If you want to map those tables to the same entity there must be one-to-one relation. It means the
DocumentIdin the second table must be unique and thus includingStartDatein the key doesn’t make sense.Also TPC inheritance is mapped differently.