[英]How to configure foreign key in Entity Framework without an inverse navigation property?
I am new to Entity Framework and I am trying to get a couple models to work.我是 Entity Framework 的新手,我正在尝试让几个模型工作。 I'll use the entities from this microsoft doc as an example, since it is the one I am following to guide myself up.我将使用此 microsoft 文档中的实体作为示例,因为它是我正在遵循的指导自己的实体。
My entities (without the non-relevant properties) look something like this:我的实体(没有不相关的属性)看起来像这样:
public class Blog
{
public Guid Id { get; set; }
public List<Post> Posts { get; set; } = new List<Post>();
}
public class Post
{
public Guid Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
}
But my database looks like this:但我的数据库看起来像这样:
Blogs
table Blogs
表
Column柱子 | Type类型 |
---|---|
Id ID | uniqueidentifier唯一标识符 |
Posts
table Posts
表
Column柱子 | Type类型 |
---|---|
Id ID | uniqueidentifier唯一标识符 |
Title标题 | nvarchar nvarchar |
Content内容 | nvarchar nvarchar |
BlogId博客 ID | uniqueidentifier唯一标识符 |
Notice the foreign key BlogId
in the Posts
table.注意Posts
表中的外键BlogId
。 Also notice that it the property is not explicitly defined in the Post
entity in code.另请注意,该属性未在代码中的Post
实体中显式定义。
When I try to do an insert using EF I get the following error:当我尝试使用 EF 进行插入时,出现以下错误:
fail: Microsoft.EntityFrameworkCore.Update[10000]失败:Microsoft.EntityFrameworkCore.Update[10000]
An exception occurred in the database while saving changes for context type 'MyNamespace.DatabaseContext'.保存上下文类型“MyNamespace.DatabaseContext”的更改时,数据库中发生异常。
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. Microsoft.EntityFrameworkCore.DbUpdateException:保存实体更改时出错。 See the inner exception for details.有关详细信息,请参阅内部异常。
Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot insert the value NULL into column 'BlogId', table 'Posts'; Microsoft.Data.SqlClient.SqlException (0x80131904):无法将值 NULL 插入到列 'BlogId'、表 'Posts' 中; column does not allow nulls.列不允许空值。 INSERT fails.插入失败。
It is trying to insert a NULL
value to the BlogId
column in the Posts
table, but I want it to grab the id from the Blog
object in which that Post
object is defined.它试图向Posts
表中的BlogId
列插入一个NULL
值,但我希望它从定义该Post
对象的Blog
对象中获取 id。 (Posts cannot exist outside a blog, so they should always be defined inside a List<Posts>
) (帖子不能存在于博客之外,因此应始终在List<Posts>
中定义它们)
What I have done is the following:我所做的如下:
public class DatabaseContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
public DatabaseContext()
{
}
public DatabaseContext(DbContextOptions<DatabaseContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.HasMany<Post>(b => b.Posts);
modelBuilder.Entity<Post>()
.HasOne<Blog>()
.WithMany(b => b.Posts)
.HasForeignKey(b => b.Id);
}
}
Here is my question: how can make EF grab the id from the blog containing the post without adding a BlogId
property to the Post
model?这是我的问题:如何在不向Post
模型添加BlogId
属性的情况下让 EF 从包含帖子的博客中获取 id? Is it even possible or am I forced to adjust my model's properties?甚至有可能还是我被迫调整模型的属性?
Also, I am using EF with a database-first approach.另外,我正在使用 EF 和数据库优先的方法。
Edit : some more information on the code.编辑:有关代码的更多信息。
The API receives the id of the Blog
and the post's properties to create a new post in that blog. API 接收Blog
的 id 和帖子的属性以在该博客中创建新帖子。 After that a commands runs that之后一个命令运行
...
var blog = await context.Set<Blog>().FindAsync(
keyValues: new object?[] { id }, cancellationToken);
blog.Posts.Add(new Post
{
Title = title,
Content = content
});
await context.SaveChangesAsync(cancellationToken);
Since you are using database first you can create the tables with foreign key and type this command由于您首先使用数据库,因此您可以使用外键创建表并键入此命令
Scaffold-DbContext "Server=localhost;Database=[DatabaseName];Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -force
and EF will generate models for you in Models folder EF 将在 Models 文件夹中为您生成模型
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.