NullReferenceException in EF 5-6.1.1 with two navigation properties to the same type

c# code-first entity-framework entity-framework-5 entity-framework-6

Question

I'd like to start by saying that I have a solution for this problem, but I also spent today determining what was causing the exception, so I thought I'd share.

assuming there are two domain entities:

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Ticket
{
    public int Id { get; set; }

    public string Name { get; set; }

    public virtual User Owner { get; set; }

    public int? LockedByUserId { get; set; }
    public virtual User LockedByUser { get; set; }

    [Timestamp]
    public byte[] ETag { get; set; }
}

The next configuration:

public class TicketConfiguration : EntityTypeConfiguration<Ticket>
{
    public TicketConfiguration()
    {
        HasRequired(x => x.Owner);

        HasOptional(x => x.LockedByUser)
            .WithMany()
            .HasForeignKey(x => x.LockedByUserId);

        Property(x => x.ETag)
            .IsConcurrencyToken(true);
    }
}

Also, this seed

protected override void Seed(DataContext context)
    {
        var users = context.Set<User>();
        var user = new User
        {
            Name = "Foo"
        };
        users.AddOrUpdate(x => x.Name, user);
        user = users.SingleOrDefault(x => x.Name == "Foo") ?? user;

        var tickets = context.Set<Ticket>();
        tickets.AddOrUpdate(x=>x.Name, new Ticket
        {
            Name = "Bar",
            Owner = user,
        });
    }

This is an exception for me:

static void Main()
    {
        var config = new Migrations.Configuration { CommandTimeout = 3600 };
        var migrator = new DbMigrator(config);
        migrator.Update();

        using (var transaction = GetTransaction()) // I've tried with and without transaction
        {
            var context = new DataContext();
            var userId = context.Set<User>().Where(x=>x.Name == "Foo").Select(x=>x.Id).Single();
            var ticket = context.Set<Ticket>().Single(x=>x.Name == "Bar");
            ticket.LockedByUserId = userId;

            context.SaveChanges(); 
            // Exception thrown here 'System.NullReferenceException' 
            //at System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.GetOtherEndOfRelationship(IEntityWrapper wrappedEntity)
            //at System.Data.Entity.Core.Objects.EntityEntry.AddRelationshipDetectedByForeignKey(Dictionary`2 relationships, Dictionary`2 principalRelationships, EntityKey relatedKey, EntityEntry relatedEntry, RelatedEnd relatedEndFrom)
            //at System.Data.Entity.Core.Objects.EntityEntry.DetectChangesInForeignKeys()
            //at System.Data.Entity.Core.Objects.ObjectStateManager.DetectChangesInForeignKeys(IList`1 entries)
            //at System.Data.Entity.Core.Objects.ObjectStateManager.DetectChanges()
            //at System.Data.Entity.Core.Objects.ObjectContext.DetectChanges()
            //at System.Data.Entity.Internal.InternalContext.DetectChanges(Boolean force)
            //at System.Data.Entity.Internal.InternalContext.GetStateEntries(Func`2 predicate)
            //at System.Data.Entity.Internal.InternalContext.GetStateEntries()
            //at System.Data.Entity.Infrastructure.DbChangeTracker.Entries()
            //at System.Data.Entity.DbContext.GetValidationErrors()
            //at System.Data.Entity.Internal.InternalContext.SaveChanges()
            //at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
            //at System.Data.Entity.DbContext.SaveChanges()
            //at EntityFrameworkFkNull.Program.Main(String[] args) in h:\Projects\Spikes\EntityFrameworkFkNull\EntityFrameworkFkNull\Program.cs:line 27
            //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()
            transaction.Complete();
        }
    }

You can attempt the complete answer here: https://github.com/mvidacovich/EntityFrameworkFkNull.

I think this is because just one of the two foreign keys that Ticket has to User is explicitly configured.

As far as I can tell from my own testing, this impacts EF 5 to EF 6.

That raises the following query: Is EF throwing an exception there expected?

1
4
7/29/2014 7:00:02 PM

Popular Answer

ZZZ_tmp
3
7/29/2014 7:00:02 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow