EF code first enforce two classes not have the same foreign key instance

I have this model:

public class A
{
      public int Id{get;set;} 
      public string Name{get;set;}     
}

public class B
{
      public int Id{get;set;} 
      public string Name{get;set;}   
      public virtual A Instance{get;set;}  
}

public class C
{
      public int Id{get;set;} 
      public string Name{get;set;}  
      public virtual A Instance{get;set;}     
}

I want that if for example I have instance A with name "MyInstance" that only one B or C class can have reference to it and if someone else try to reference "MyInstance" the code will throw exception. How can I configure it?

Answers


Such constraint can't be defined in the EF. You need to enforce the constraint in your code.

One possible solution:

public class A {
    private B _referenceB;
    private C _referenceC;

    public int Id { get; set; } 

    public string Name { get; set; }

    public virtual B ReferenceB {
        get { return _referenceB; }
        set { 
                if (this.ReferenceC != null) {
                   throw new InvalidOperationException();
                }
                _referenceB = value;
            }
        }

    public virtual C ReferenceC {
        get { return _referenceC; }
        set { 
                if (this.ReferenceB != null) {
                   throw new InvalidOperationException();
                }
                _referenceC = value;
            }
        }
    }
}

Alternative solution:

public class ReferenceBase { }
public class B : ReferenceBase { ... }
public class C : ReferenceBase { ... }
public class A {
    public virtual ReferenceBase  Reference { get; set; }
    //implement a custom setter if you want to throw exception
}

Need Your Help

Cloud IDE for java?

java ide cloud bitcoin

I’m currently developing code meant to interact with the API of the Bitcoin exchange with an algorithm deciding whether to buy or sell and all. However, I can’t have my laptop running 24/7, so I was