简体   繁体   中英

How to properly create an EF One-to-Zero-or-One relationship with navigation properties on both ends?

In my model I have two objects: Lead and Work . Lead may have a related Work , but Work must have a related Lead . How do I properly express this using EF Code First and Fluent API? I've spent most of the day so far going in circles trying to do this, but I'm getting nowhere. The problem (maybe?), is that I need to have the navigation properties on both sides of the relationship. Here's how I've got my objects configured so far:

public class Lead {
    public int Id { get; set; }
    public int? WorkId { get; set; }
    public virtual Work Work { get; set; }
}

public class Work {
    public int Id { get; set; }
    //public int LeadId { get; set; } <- I think this is necessary?
    public virtual Lead Lead { get; set; }
}

// this seems to make a one-to-one relationship, but it's setting
// the column references as the Id columns on both sides, so it's wrong...
// Also causes this exception:
// A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: 'Id'.
this.HasOptional(t => t.Work).WithRequired(t => t.Lead);

Attempting to reverse engineer a test database yields a One-to-Many relationship, which is not what I want. I'd appreciate suggestions on how to properly configure the relationship.

If lead is a principal (Lead must exist first), the classes could look like this.

public class Lead {
    public int Id { get; set; }
    public virtual Work Work { get; set; }
}

public class Work {
    [Key, ForeignKey("Lead")]
    public int Id { get; set; }
    public virtual Lead Lead { get; set; }
}

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