简体   繁体   English

如何在没有反向导航属性的实体框架中配置外键?

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

相关问题 没有导航属性的外键实体框架数据注释 - Entity framework data annotation of foreign key without a navigation property 具有复合外键的实体框架导航属性 - Entity Framework Navigation Property with Composite Foreign Key 实体框架中的逆属性和外键有什么区别? - what is difference between inverse property and foreign key in entity framework? 实体框架,更改外键,但导航属性不变 - entity framework, change foreign key but navigation property not changing 实体框架 - 未设置外键(0 / null)但导航属性不为空 - Entity Framework - Foreign Key not set (0 / null) but navigation property is not null 使用UserName作为实体框架中的外键创建ApplicationUser导航属性 - Creating an ApplicationUser navigation property using UserName as the foreign key in Entity Framework 在实体框架中将表单导航属性迁移到外键 - Migrating form Navigation Property to Foreign Key in Entity Framework 实体框架可以将同一列映射到导航属性和外键吗 - Can Entity Framework map the same column to a Navigation Property and a Foreign Key 在没有所有键/外键的情况下在实体框架中创建导航属性 - Create Navigation Property in Entity Framework Without all keys/foreign keys 如何在Entity Framework中为同一表配置导航属性? - How do I configure a navigation property to the same table in Entity Framework?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM