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

房东的猫 提交于 2019-12-05 17:50:48

The workaround is to have an "OwnerId" property on Ticket. (See fix branch in the solution in github)

So, Ticket becomes:

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

    public string Name { get; set; }

    public int? OwnerId { 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; }
}

And Ticket's configuration changes to:

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

        Property(x => x.OwnerId)
            .HasColumnName("Owner_Id");

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

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

Notice the explicit OwnerId now. See this for the full (fixed) solution: https://github.com/mvidacovich/EntityFrameworkFkNull/tree/Fix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!