Namindu Sanchila
Namindu Sanchila

Reputation: 414

One-to-many relationship getting error in Entity Framework Core when trying to insert data

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)

Upvotes: 2

Views: 9092

Answers (1)

Namindu Sanchila
Namindu Sanchila

Reputation: 414

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

Upvotes: 3

Related Questions