2

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

There are two tables:

  1. Post
  2. Attachment

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

  1. Adding records to the Post table, then after that
  2. using that post-Id. update the Attachment table

Here is the exception thrown

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.

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'

And here the my 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);    
    }    
}

And here are the two entity classes :

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; }    
}

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Namindu Sanchila
  • 414
  • 1
  • 9
  • 23
  • 1
    Where did u assigned foreign key of attachment entity in post model? like `public int AttachmentId {get;set;}` in post model – er-sho Jul 28 '18 at 05:33
  • The Relationship is One post has many Attachment, But One Attachment has unique post – Namindu Sanchila Jul 28 '18 at 05:37
  • 1
    Visit here night be help you https://github.com/aspnet/EntityFrameworkCore/issues/9552 – er-sho Jul 28 '18 at 05:38
  • Its not help for me – Namindu Sanchila Jul 28 '18 at 05:54
  • 1
    try to remove `public int PostId { get; set; }` from `Attachment` model bcoz it will be created automatically by EF Core – er-sho Jul 28 '18 at 06:06
  • Still the same. I remove public int PostId { get; set; } – Namindu Sanchila Jul 28 '18 at 06:09
  • replace this `modelBuilder.Entity() .HasOne(p => p.Posts) .WithMany(c => c.Attachment) .HasForeignKey(p => p.Id); ` with `modelBuilder.Entity() .HasOne(p => p.Posts) .WithMany(c => c.Attachment);` in `OnModelCreating` means remove `HasForeignKey` and also remove `postId` property from `Attachment` model – er-sho Jul 28 '18 at 06:12
  • Add-migration and update database i got this exception System.InvalidOperationException: To change the IDENTITY property of a column, the column needs to be dropped and recreated. – Namindu Sanchila Jul 28 '18 at 06:16
  • I am new for the EF. – Namindu Sanchila Jul 28 '18 at 06:16
  • please provide your `AddPost` in `PostRepo`. so i can try from my side. add this method in post – er-sho Jul 28 '18 at 06:22
  • public Posts AddPost(Posts post) { try { _context.Posts.Add(post); _context.SaveChanges(); return post; } catch(Exception e) { throw new Exception($"Post Not Added. {e}"); } } – Namindu Sanchila Jul 28 '18 at 06:24

1 Answers1

3

I fixed This.

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);
Namindu Sanchila
  • 414
  • 1
  • 9
  • 23