MVC3 Optional Bidirectional relationship code first

343 views Asked by At

What I have is something like

public class BuildingUnit
{
    public int ID { get; set; }
    *irrelevant stuff removed*
    public virtual BuildingUnitInsurance UnitInsurance { get; set; }
}


public class BuildingUnitInsurance
{
    public int ID { get; set; }
    *irrelevant stuff removed*
    public virtual BuildingUnit BuildingUnit { get; set; }
}

What I want to do is have the relationship from the BuildingUnit to the BuildingUnitInsurance be optional, but if it does exist, the relationship from BuildingUnitInsurance to BuildingUnit must exist. I've tried a whole bunch of things with annotations and fluent api but I haven't really gotten anywhere.

The actual business case here is having a view displaying information from the BuildingUnit class, and then on that page it is possible to click a button and pop up a modal to add insurance information. Clicking the 'add insurance' button on that modal will post the insurance information to the controller and at that point it should be saved and the relationship should be created between the BuildingUnit and the BuildingUnitInsurance. Any help with the controller code would be great too since I don't really know what I would have to do there to make those relationships happen.

1

There are 1 answers

0
kingdango On

You need to have a one-to-zero-or-one relationship for BuildingUnit and a one-to-one required for BuildingUnitInsurance. The code below should help you and if not read more on Configuring Relationships.

public class BuildingUnit
{
    [Key]
    public int ID { get; set; }

    [ForeignKey("UnitInsurance")]
    public virtual int? UnitInsuranceId { get; set; }

    public virtual BuildingUnitInsurance UnitInsurance { get; set; }
}


public class BuildingUnitInsurance
{
    [Key]
    public int ID { get; set; }

    [Required]
    [ForeignKey("BuildingUnit")]
    public virtual int BuildingUnitId { get; set; }

    public virtual BuildingUnit BuildingUnit { get; set; }
}

And then in your OnModelCreating handler:

modelBuilder.Entity<BuildingUnit>.HasOptional(x => x.UnitInsurance).WithRequired();
modelBuilder.Entity<BuildingUnitInsurance>.HasRequired(x => x.BuildingUnit).WithOptional();