【问题标题】:EF6: Configure complex mapping for entities (code first)EF6:为实体配置复杂映射(代码优先)
【发布时间】:2016-06-16 15:30:40
【问题描述】:

我有两个想要使用 EF6 fluent API 配置的数据库实体。

public class Account
{
    public Int32 Id { get; set; }

    public Int32? LastOperationId { get; set; }
    public virtual Operation LastOperation { get; set; }

    public virtual List<Operation> Operations { get; set; }
}

public class Operation
{
    public Int32 Id { get; set; }

    public Int32? AccountId { get; set; }
    public virtual Account Account { get; set; }
}

对于任何配置,在尝试将帐户实体实例插入数据库时​​,我总是会收到错误“无法确定相关操作的有效排序”:

var account = new Account();
var operation = new Operation();

account.Operations = new List<Operation>() { operation };
account.LastOperation = operation;

dbContext.Accounts.Add(account);
dbContext.SaveChanges();

【问题讨论】:

    标签: c# sql .net entity-framework


    【解决方案1】:

    幸运的是,EF 推断出外键列 AccountIdLastOperationId,所以这对我有用:

    modelBuilder.Entity<Operation>()
    .HasKey(x => x.Id)
    .HasOptional(x => x.Account)
    .WithMany(x => x.Operations);
    
    modelBuilder.Entity<Account>()
    .HasKey(x => x.Id)
    .HasOptional(x => x.LastOperation);
    

    【讨论】:

      【解决方案2】:

      这正是您在 Code-First 中所需要的组合:

      public class Account
      {
          // One to one to one relationship (shared PK)
           public int Id { get; set; }
      
           // One to one to one relationship (shared PK)
           public virtual Operation Operation { get; set; }
      
          // One to many relationship foreign Key
          [InverseProperty("AccountForList")]
           public virtual List<Operation> Operations { get; set; }
         }
      
         public class Operation
         {
          // One to one to one relationship (shared PK)
          [ForeignKey("Account")]
           public Int32 Id { get; set; }
      
           // One to one to one relationship (shared PK)
           public virtual Account Account { get; set; }
      
           // One to many relationship foreign Key
           public Int32? AccountForListId { get; set; }
      
           // One to many relationship foreign Key
           [ForeignKey("AccountForListId")]
           public virtual Account AccountForList { get; set; }
           }
      

      帐户表:列名:Id

      操作表:列名Id(与Account共享)、AccountForListId(1..n)

      【讨论】:

        猜你喜欢
        • 2013-01-21
        • 1970-01-01
        • 2011-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-27
        • 1970-01-01
        相关资源
        最近更新 更多