简体   繁体   English

Entity Framework Core - 手动将 id 分配给链接的实体

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

I've reviewed other related questions on StackOverflow, but I haven't found one that matches my exact question or scenario.我已经查看了 StackOverflow 上的其他相关问题,但没有找到与我的确切问题或场景相符的问题。

I have an JavaScript front-end where I have two entities that are linked, so in the front-end I have JSON objects that get 'linked' to each other like this:我有一个 JavaScript 前端,其中有两个链接的实体,因此在前端我有 JSON 对象,它们像这样相互“链接”:


entity1实体1

name = "something"名称 = "东西"

entity2Id = 0 entity2Id = 0

entity2实体2

1st record第一个记录

id = 0编号 = 0

name = "something else"名称 = "别的东西"

2nd record第二记录

id = 1编号 = 1

name = "something else again" name = "又是别的东西"


I then send the JSON to a .NET back end, and the idea is that as I'm manually specifying the primary key for entity2 and setting that as the 'foreign key' reference in my entity1, Entity Framework then somehow needs to generate a valid id for entity2, and maintain a reference to that id in the entity2id property of entity1.然后我将 JSON 发送到 .NET 后端,想法是当我手动指定 entity2 的主键并将其设置为我的 entity1 中的“外键”引用时,Entity Framework 需要以某种方式生成一个entity2 的有效 ID,并在 entity1 的entity2id属性中维护对该 ID 的引用。

I suspect I may be getting this all horribly wrong and that there's a fairly standard approach to achieving what I'm trying to do.我怀疑我可能把这一切都弄错了,并且有一种相当标准的方法来实现我想要做的事情。 What should I do to achieve the desired result?我应该怎么做才能达到预期的结果? (I'm using a SQLite database, which probably doesn't make a difference.) (我使用的是 SQLite 数据库,这可能没有什么区别。)

You have a one-to-many relationship there.你在那里有one-to-many关系。 To make it easier to explain I'll change your Entit1 to Book and Entity2 to Genre .为了更容易解释,我会将您的 Entit1 更改为Book并将 Entity2 更改为Genre So something like this:所以像这样:

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

You can then use the FluentApi to configure the relationship (most importantly the FK key on Books from Genres然后您可以使用 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);
}

Now we can achieve your two scenarios:现在我们可以实现您的两个场景:

1 - Create a new Book along with a new Genre 1 - 创建Book和新Genre

2 - Create a new Book that uses an existing Genre on db 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();
}

After saving you'll have this in the database:保存后,您将在数据库中拥有它:

保存后查询结果

You'll probably have to change your front-end to start sending also the Genre object along.您可能必须更改前端才能开始同时发送Genre对象。 In cases where it's a new one, the Id will be missing.如果是新的, Id将丢失。 When you serialize it into your c# types, you can figure it out if you have to create new instance or just maybe check if the Id front-end passed exists or not.当您将其序列化为 c# 类型时,您可以弄清楚是否必须创建新实例,或者只是检查传递的 Id 前端是否存在。

Remarks: I did all this using Sqlite and the EF core packages version 2.2.0-preview1-35029 .备注:我使用Sqlite和 EF 核心包版本2.2.0-preview1-35029完成了所有这些。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM