簡體   English   中英

實體框架6首先編寫代碼-參照另一個現有實體添加實體

[英]Entity framework 6 code first - Add entity with reference to another existing entity

說我的數據庫中有以下模型:

public class LetterEntity
{   
    public int Id {get; set;}

    public string Content {get; set;}

    public List<Destination> Destinations {get; set;}

    public virtual Folder Folder {get; set;}

    public int FolderId {get; set;}
}

現在,我想向客戶添加一個新的字母到我的數據庫中:

public class SendLetterRequest
{
    public string Content {get; set;}

    public List<int> DestinationsIds {get; set;}
}

public void SaveLetterToDatabase(SendLetterRequest letter)
{
    var letterEntity = new LetterEntity 
    {
        Content = letter.Content;
        FolderId = 1;

        // How to insert the Destinations Ids in a way that I don't have to load all of those destinations to the context?
    }

    context.Set<LetterEntity>().Add(letterEntity);

    context.SaveChanges();
}

我知道,如果一個LetterEntity僅具有一個Destination對象,我可以將其設置為外鍵值,並且插入將起作用(就像我對FolderId所做的那樣)。 使用實體列表時,如何完成操作-如何告訴EF這些ID已存在於數據庫中,而又不將所有ID都獲取到上下文中,從而不會重新創建它們?

編輯:

我的目的地模型-

public void Destination
{
    // Manual key
    public int Address {get; set;}

    public string DestinationName {get; set;}

    public string Information {get; set;}
}

嗯,您可能知道,在EF中有兩種定義many-to-many方法。

(1)隱式鏈接表

這就是您所使用的。 您僅顯式創建兩個實體,通過導航屬性/和/或模型配置定義關系,並讓EF維護所謂的“鏈接”表。 這很容易,但是缺點是您無權訪問該表,因此添加相關項的唯一方法是實際加載所需的實體並將其添加到導航屬性集合中。

(2)顯式鏈接表

在這里,您可以明確定義鏈接實體並配置2 one-to-many關系。 這樣,您便可以訪問,並且可以添加未加載其他實體的相關記錄。

例如,在您的情況下,可能是這樣的:

模型:

public class LetterEntity
{
    public int Id { get; set; }
    // ....
    public List<LetterDestinationLink> Links { get; set; }
}

public class Destination
{
    public int Id { get; set; }
    // ....
    public List<LetterDestinationLink> Links { get; set; }
}

public class LetterDestinationLink
{
    [Key]
    [Column(Order = 0)]
    public int LetterId { get; set; }
    [Key]
    [Column(Order = 1)]
    public int DestinationId { get; set; }
    public LetterEntity Letter { get; set; }
    public Destination Destination { get; set; }
}

語境:

public class YourDbContext : DbContext
{
    public DbSet<LetterEntity> LetterEntities { get; set; }
    public DbSet<Destination> Destinations { get; set; }
    public DbSet<LetterDestinationLink> LetterDestinationLinks { get; set; }
}

用例:

List<int> destinationIds = ...;
var letterEntity = new LetterEntity { ... };
letterEntity.Links = destinationIds.Select(destinationId =>
    new LetterDestinationLink { Letter = letterEntity, DestinationId = destinationId })
    .ToList();
context.Set<LetterEntity>().Add(letterEntity);
context.SaveChanges();

暫無
暫無

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

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