efcore icon indicating copy to clipboard operation
efcore copied to clipboard

DbUpdateException while adding an entity with one-to-one relationship

Open mkucera47 opened this issue 10 years ago • 1 comments

I have the following model:

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public BlogImage BlogImage { get; set; }
}

public class BlogImage
{
    public int BlogImageId { get; set; }
    public byte[] Image { get; set; }
    public string Caption { get; set; }

    public int BlogId { get; set; }
    public Blog Blog { get; set; }
}

class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<BlogImage> BlogImages { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .HasOne(b => b.BlogImage)
            .WithOne(i => i.Blog)
            .HasForeignKey<BlogImage>(i => i.BlogId);
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite("Filename=blogs.db");
    }
}

With the following code:

Blog blog = new Blog()
{
    Url = "myblog.com",
    BlogImage = new BlogImage()
    {
        Caption = "My image caption",
        Image = null
    }
};
blog.BlogImage.Blog = blog;

using (BloggingContext db = new BloggingContext())
{
    //db.Blogs.Add(blog); // This works
    db.BlogImages.Add(blog.BlogImage); // This does not
    Console.WriteLine(db.SaveChanges()); // Exception thrown here
}

I get this exception:

Microsoft.Data.Entity.DbUpdateException was unhandled
  HResult=-2146233088
  Message=An error occurred while updating the entries. See the inner exception for details.
  Source=EntityFramework.Relational
  StackTrace:
       at Microsoft.Data.Entity.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
       at Microsoft.Data.Entity.Update.Internal.BatchExecutor.Execute(IEnumerable`1 commandBatches, IRelationalConnection connection)
       at Microsoft.Data.Entity.Storage.RelationalDatabase.SaveChanges(IReadOnlyList`1 entries)
       at Microsoft.Data.Entity.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList`1 entriesToSave)
       at Microsoft.Data.Entity.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
       at Microsoft.Data.Entity.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
       at Microsoft.Data.Entity.DbContext.SaveChanges()
       at EF7_Issue_2.Program.Main(String[] args) in c:\users\martin\documents\visual studio 2015\Projects\EF7-Issue-2\EF7-Issue-2\Program.cs:line 28
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 
       ErrorCode=-2147467259
       HResult=-2147467259
       Message=SQLite Error 19: 'FOREIGN KEY constraint failed'
       Source=Microsoft.Data.Sqlite
       SqliteErrorCode=19
       StackTrace:
            at Microsoft.Data.Sqlite.Interop.MarshalEx.ThrowExceptionForRC(Int32 rc, Sqlite3Handle db)
            at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader(CommandBehavior behavior)
            at Microsoft.Data.Sqlite.SqliteCommand.ExecuteDbDataReader(CommandBehavior behavior)
            at System.Data.Common.DbCommand.ExecuteReader()
            at Microsoft.Data.Entity.Storage.Internal.RelationalCommand.<>c__DisplayClass17_0.<ExecuteReader>b__0(DbCommand cmd, IRelationalConnection con)
            at Microsoft.Data.Entity.Storage.Internal.RelationalCommand.Execute[T](IRelationalConnection connection, Func`3 action, String executeMethod, Boolean openConnection, Boolean closeConnection)
            at Microsoft.Data.Entity.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, Boolean manageConnection)
            at Microsoft.Data.Entity.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
       InnerException: 

Is this a bug or is it wrong to use db.BlogImages.Add(blog.BlogImage); (which causes the exception) instead of db.Blogs.Add(blog); (which works)?

I am using 7.0.0-rc1-final, .Net Framework 4.5.2 and Visual Studio 2015.

mkucera47 avatar Dec 12 '15 20:12 mkucera47

Hey,

This is currently by design. When you add an entity to the context, by default, it recursively adds children/dependents to the context too. There are overloads of Add which allow you to specify a "graph behavior" to control what gets added.

BTW several folks have found this behavior confusing, so we are discussing changing it at the moment.

~Rowan

rowanmiller avatar Dec 16 '15 17:12 rowanmiller