簡體   English   中英

EF6:為實體配置復雜映射(代碼優先)

[英]EF6: Configure complex mapping for entities (code first)

我有兩個db實體,我想使用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();

幸運的是,EF推斷外鍵列AccountIdLastOperationId ,所以這對我LastOperationId

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

這是您在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; }
     }

帳戶表:columnname:Id

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM