简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM