【问题标题】:Entity Framework Code First - Single entity map to multiple tables without common keyEntity Framework Code First - 单个实体映射到多个表,没有公共键
【发布时间】:2012-02-03 05:37:26
【问题描述】:

在将一个实体映射到现有数据库中的多个表时,我遇到了关于 EF 代码第一个版本的问题。

Table1: (primaryKey is IdDocument)
----------------------------
IdDocument | CreationDate
----------------------------

Table 2: (primaryKey is on IdDocument and StartDate)
------------------------------------------------------------
IdDocument | StartDate | Label | LastUpdate 
------------------------------------------------------------

在单个实体中,我试图更新数据库中的信息。以下是实体类。

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; }
}

以下是同一实体的 DbModelBuilder,

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);
}

无法更新 Table1。

【问题讨论】:

  • 我已尝试格式化您的代码,使其更具可读性。我希望它仍然是正确的。

标签: entity-framework-4 code-first


【解决方案1】:

如果它们在所有表中没有相同的主键,则无法映射继承。如果要将这些表映射到同一个实体,则必须存在一对一的关系。这意味着第二个表中的DocumentId 必须是唯一的,因此在键中包含StartDate 没有意义。

TPC 继承也是mapped differently

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多