[英]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.