【发布时间】:2018-07-28 05:09:57
【问题描述】:
我正在尝试将数据添加到一对多关系表中。但是有一个例外。
有两个表:
- 发布
- 附件
帖子有很多附件,但一个附件有一个独特的帖子。我要试试:
- 将记录添加到
Post表,然后在此之后 - 使用该帖子 ID。更新
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(Tuple2 parameters)3 操作,Func
at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func3 verifySucceeded) at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func2 操作) 在 Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable1 commandBatches, IRelationalConnection connection) at Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IReadOnlyList1 个条目) 在 Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList`1 entriesToSave) 在 Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(布尔型 acceptAllChangesOnSuccess) 在 Microsoft.EntityFrameworkCore.DbContext.SaveChanges(布尔型 acceptAllChangesOnSuccess) 在 Microsoft.EntityFrameworkCore.DbContext.SaveChanges() 在 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)
【问题讨论】:
-
你在哪里分配了post模型中附件实体的外键?像
public int AttachmentId {get;set;}在后期模型中 -
关系是一个帖子有很多附件,但一个附件有唯一的帖子
-
对我没有帮助
-
尝试从
Attachment模型中删除public int PostId { get; set; },因为它将由EF Core自动创建
标签: c# asp.net-core entity-framework-core