簡體   English   中英

Entity Framework Core - 手動將 id 分配給鏈接的實體

[英]Entity Framework Core - manually assigning id's to linked entities

我已經查看了 StackOverflow 上的其他相關問題,但沒有找到與我的確切問題或場景相符的問題。

我有一個 JavaScript 前端,其中有兩個鏈接的實體,因此在前端我有 JSON 對象,它們像這樣相互“鏈接”:


實體1

名稱 = "東西"

entity2Id = 0

實體2

第一個記錄

編號 = 0

名稱 = "別的東西"

第二記錄

編號 = 1

name = "又是別的東西"


然后我將 JSON 發送到 .NET 后端,想法是當我手動指定 entity2 的主鍵並將其設置為我的 entity1 中的“外鍵”引用時,Entity Framework 需要以某種方式生成一個entity2 的有效 ID,並在 entity1 的entity2id屬性中維護對該 ID 的引用。

我懷疑我可能把這一切都弄錯了,並且有一種相當標准的方法來實現我想要做的事情。 我應該怎么做才能達到預期的結果? (我使用的是 SQLite 數據庫,這可能沒有什么區別。)

你在那里有one-to-many關系。 為了更容易解釋,我會將您的 Entit1 更改為Book並將 Entity2 更改為Genre 所以像這樣:

public class Book
{
    public int Id { get; set; }
    public string Name { get; set; }

    public int GenreId { get; set; }
    public Genre Genre { get; set; }
}

public class Genre
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Book> Books { get; set; }
}

然后您可以使用 FluentApi 來配置關系(最重要的是Books from Genres上的 FK 鍵

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Book>()
        .HasOne(p => p.Genre)
        .WithMany(b => b.Books)
        .HasForeignKey(p => p.GenreId);
}

現在我們可以實現您的兩個場景:

1 - 創建Book和新Genre

2 - 創建一Book使用 db 上現有Genre Book

var bookWithNewGenre = new Book
{
    Name = "Book 1",

    // Here we are creating a new Genre, without Id.
    // GenreId here will have the default value of 0, 
    // which EF will use to find out that it has to be created
    Genre = new Genre { Name = "Mistery"}   
};

var bookWithExistingFictionGenre = new Book
{
    Name = "Book 2",

    // Here we are specifying the GenreId = 1 which already exists in the Database
    GenreId = 1,

    // You don't need to set this to null
    // but I like doing it to make EF and my code clear that I'm using an existing Genre
    Genre = null
};

using (var context = new BookContext())
{
    context.Books.Add(bookWithNewGenre);
    context.Books.Add(bookWithExistingFictionGenre);
    await context.SaveChangesAsync();
}

保存后,您將在數據庫中擁有它:

保存后查詢結果

您可能必須更改前端才能開始同時發送Genre對象。 如果是新的, Id將丟失。 當您將其序列化為 c# 類型時,您可以弄清楚是否必須創建新實例,或者只是檢查傳遞的 Id 前端是否存在。

備注:我使用Sqlite和 EF 核心包版本2.2.0-preview1-35029完成了所有這些。

暫無
暫無

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

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