One-to-one relation + on-to-many relation using same entity

c# entity-framework-core

Question

I'm trying to create a customer entity that has multiple contact persons, as well as one primary contact person, but I can't seem to add the migration, as I'm getting the following error:

Unable to determine the relationship represented by navigation property 'ContactPerson.Customer' of type 'Customer'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

Customer

public class Customer
{
    public Guid CustomerId { get; set; }
    public string Name { get; set; }
    public DateTime CreateDate { get; set; }
    public string City { get; set; }
    public string Address { get; set; }

    // Contact person data
    public virtual ContactPerson PrimaryContactPerson { get; set; }
    public virtual ICollection<ContactPerson> ContactPersons { get; set; }
}

ContactPerson

public class ContactPerson
{
    public Guid ContactPersonId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public virtual Customer Customer { get; set; }
}

I tried adding the foreign keys myself, and annotating the foreign key property with my entity, on both the Customer entity as well as the ContactPerson entity, like this:

public class ContactPerson
{
    public Guid ContactPersonId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    [ForeignKey("Customer")]
    public Guid CustomerId { get; set; }
    public virtual Customer Customer { get; set; }
}

But it doesn't seem to make any difference, I'm still getting the same error. How can it be that EF can't determine the relationship?

I suppose it has something to do with the one-to-one relation simultaneously existing with the one-to-many relation, but I can't seem to wrap my head around this issue. Advice and suggestion are highly appreciated!

If I comment out the PrimaryContactPerson property, EF adds the migration just fine, so I'm positive that this has something to do with the two different relations.

1
0
5/29/2018 9:52:01 PM

Popular Answer

I managed to solve my issue using the Entity Framework Fluent API, like this:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<ContactPerson>(e =>
        e.HasOne(r => r.Customer).WithMany(c => c.ContactPersons)
    );
}
0
3/7/2018 7:24:25 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