我正在尝试将数据添加到一对多关系表中。但是有一个例外。
有两个表:
该帖子有很多附件,但一个附件有一个独特的帖子。我要尝试:
Post
表中Attachment
表这里是引发异常的地方
InvalidOperationException:实体类型“ Posts”上的属性“ Id”具有一个临时值。要么显式设置一个永久值,要么确保将数据库配置为为此属性生成值。
在Microsoft.EntityFrameworkCore.Update.Internal.CommandBatchPreparer.Validate(ModificationCommand ModifyCommand)
在Microsoft.EntityFrameworkCore.Update.Internal.CommandBatchPreparer.d__8.MoveNext()
在Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(元组2 parameters)
3操作,函数
at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func3 verifySucceeded) at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func
2操作) 在Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable1 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() 在GradChat.Data.Repo.PostRepository.PostRepo.AddPost(帖子发布)中的C:\ Users \ kokuadmin \ source \ repos \ GradChat \ GradChat.Data.Repo \ PostRepository \ PostRepo.cs:第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)
答案 0 :(得分:1)
我解决了这个问题。
以此更改OnModelCreating()
。谢谢帮我。只需将.HasForeignKey(p=> p.Id)
更改为.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);