Search code examples
c#entity-frameworkpocoef-fluent-api

one-zero-one relation ef codefrist


i have 3 class

public class StockDef
{
    public int Id { get; set; }
    public int StockType { get; set; }
    public virtual OfficeStock SayanStock { get; set; }
    public virtual AgentStock AgentStock { get; set; }
    //....
}

public class OfficeStock
{
    public virtual StockDef StockDef { get; set; }
    //....
}

public class AgentStock
{
    public virtual StockDef StockDef { get; set; }
    //......
}

every StockDef object definitely have (one OfficeStock or one AgentStock).
and every OfficeStock definitely have one StockDef.
and every AgentStock definitely have one StockDef.
how can I implement this, in EF Code first by fluent API?
tnx


Solution

  • You can't configure StockDef (the constraint "only one property can be compiled") with fluent api, you have to add a custom validation implementing IValidatableObject interface.

    You can also add a constraint (a trigger?) on the database so you can avoid that someone else inserts wrong records.

    Also, about 1-1 relationship configuration you can have a look here Code First migration when entities have cross references with foreign keys