尝试插入数据时,Entity Framework Core中的一对多关系出现错误 [英] One-to-many relationship getting error in Entity Framework Core when trying to insert data

查看:324
本文介绍了尝试插入数据时,Entity Framework Core中的一对多关系出现错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数据添加到一对多关系表中.但是有一个例外.

I'm trying to add data to one-to-many relationship tables. But there is an exception.

有两个表:

  1. 发布
  2. 附件

该帖子有许多附件,但一个附件有一个独特的帖子.我要尝试:

The Post has many Attachment but one Attachment has one unique post. I'm going to try:

  1. 将记录添加到Post表中,然后在此之后
  2. 使用该后置ID.更新Attachment
  1. Adding records to the Post table, then after that
  2. using that post-Id. update the Attachment table

这是引发异常的地方

InvalidOperationException:实体类型"Posts"上的属性"Id"具有一个临时值.要么显式设置一个永久值,要么确保将数据库配置为为此属性生成值.

InvalidOperationException: The property 'Id' on entity type 'Posts' has a temporary value. Either set a permanent value explicitly or ensure that the database is configured to generate values for this property.

在Microsoft.EntityFrameworkCore.Update.Internal.CommandBatchPreparer.Validate(ModificationCommand modifyCommand)
在Microsoft.EntityFrameworkCore.Update.Internal.CommandBatchPreparer.d__8.MoveNext()
在Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(Tuple 2 parameters)
at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func
3操作,Func 3 verifySucceeded) at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func 2操作) 在Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable 1 commandBatches, IRelationalConnection connection) at Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IReadOnlyList 1个条目) 在Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList`1 entryToSave) 在Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess) 在Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess) 在Microsoft.EntityFrameworkCore.DbContext.SaveChanges() 在C:\ Users \ kokuadmin \ source \ repos \ GradChat \ GradChat.Data.Repo \ PostRepository \ PostRepo.cs:27行的GradChat.Data.Repo.PostRepository.PostRepo.AddPost(帖子发布)

at Microsoft.EntityFrameworkCore.Update.Internal.CommandBatchPreparer.Validate(ModificationCommand modificationCommand)
at Microsoft.EntityFrameworkCore.Update.Internal.CommandBatchPreparer.d__8.MoveNext()
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(Tuple2 parameters)
at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func
3 operation, Func3 verifySucceeded) at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func2 operation) at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable1 commandBatches, IRelationalConnection connection) at Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IReadOnlyList1 entries) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList`1 entriesToSave) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess) at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess) at Microsoft.EntityFrameworkCore.DbContext.SaveChanges() at GradChat.Data.Repo.PostRepository.PostRepo.AddPost(Posts post) in C:\Users\kokuadmin\source\repos\GradChat\GradChat.Data.Repo\PostRepository\PostRepo.cs:line 27'

这是我的OnModelCreating()

protected override void OnModelCreating(ModelBuilder modelBuilder)
{    
      modelBuilder.Entity<Posts>()
          .HasOne(p => p.User)
          .WithMany(c => c.Posts)
          .HasForeignKey(p => p.Id);    

      modelBuilder.Entity<Attachment>()
          .HasOne(p => p.Posts)
          .WithMany(c => c.Attachment)
          .HasForeignKey(p => p.Id);    
    }    
}

这是两个实体类:

public class Attachment
{
    public int Id { get; set; }    
    public string FileName { get; set; }    
    public string FileTye { get; set; }    
    public virtual Posts Posts { get; set; }    
    public int PostId { get; set; }    
}

public class Posts
{     
    public int Id { get; set; }    
    public string Title { get; set; }    
    public string Content { get; set; }    
    public virtual User User { get; set; }    
    public int UserId { get; set; }    
    public virtual ICollection<Attachment> Attachment { get; set; }    
}

我正在使用Microsoft.EntityFramework.Core.SqlServer(2.0.1)

I'm using Microsoft.EntityFramework.Core.SqlServer (2.0.1)

推荐答案

我已修复此问题.

以此更改OnModelCreating().谢谢帮帮我.只需将.HasForeignKey(p=> p.Id)更改为.HasForeignKey(p => p.UserId);

change the OnModelCreating()as this. Thanks for Help me. just change, .HasForeignKey(p=> p.Id) to .HasForeignKey(p => p.UserId);

 modelBuilder.Entity<Posts>()
          .HasOne(p => p.User)
          .WithMany(c => c.Posts)
          .HasForeignKey(p => p.UserId);

      modelBuilder.Entity<Attachment>()
        .HasOne(p => p.Posts)
        .WithMany(c => c.Attachment);

这篇关于尝试插入数据时,Entity Framework Core中的一对多关系出现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆