0

im using an adapter to be able to plug interfaces rather than concrete types into dbcontext. the adapter works on its own, but im having trouble with getting the any one-to-one (parent child) relationships to be saved into the database:

Exception Source

public void SaveDomain(IDomain domain){
    _entityRepositor = new Donors();
    _entityRepositor.DomainReps.Add(new DomainRep(domain));                
}

InvalidOperationException

Conflicting changes to the role 'DomainRep_TopLevelDomainRep_Target' of the relationship 'Edonics.Repositor.DomainRep_TopLevelDomainRep' have been detected.

The Foreign Key Properties and the Navigation Properties Should Be in Sync?

public class DomainRep: IDomain
{
    private readonly IDomain _adaptee;        


    public DomainRep(IDomain adaptee)
    {
        _adaptee = adaptee;
    }

    [NotMapped]
    public IDomain Adaptee
    {
        get { return _adaptee; }
    }

    public string Id
    {
        get { return _adaptee.Id; }
        set { _adaptee.Id = value; }
    }

    public string TopLevelDomainRepId
    {
        get { return _adaptee.Tld.Id; }

        set { }
    }

    [ForeignKey("TopLevelDomainRepId")]
    public TopLevelDomainRep TopLevelDomainRep
    {
        get { return new TopLevelDomainRep(Tld); }
        set { Tld = value.Adaptee; }
    }

    public ITopLevelDomain Tld
    {
        get { return _adaptee.Tld; }
        set { _adaptee.Tld = value; }
    }

    public string SecondLevelDomainRepId
    {
        get { return _adaptee.Sld.Id; }  
        
        set { } 
    }

    [ForeignKey("SecondLevelDomainRepId")]
    public SecondLevelDomainRep SecondLevelDomainRep
    {
        get { return new SecondLevelDomainRep(Sld); }
        set { Sld = value.Adaptee; }
    }

    public ISecondLevelDomain Sld
    {
        get { return _adaptee.Sld; }
        set { _adaptee.Sld = value; }
    }
    
}

Any ideas?

Community
  • 1
  • 1
Cel
  • 6,467
  • 8
  • 75
  • 110

1 Answers1

5

Your adapter pattern interfere with how EF works. You are providing a different implementation for the navigational properties of the entity. For example, if you access TopLevelDomainRep property several times it will return multiple instances but with the same ID/Entity Key. EF handles only single instance per context for a given primary key value.

Either you create a domain layer on top of EF entities or you use EF entities the way it was expected to.

Eranga
  • 32,181
  • 5
  • 97
  • 96
  • You are right - I changed the getter of `TopLevelDomainRep` to `get { return _topLevelDomainRep ?? (_topLevelDomainRep = new TopLevelDomainRep(Tld)); }` and it started to save the data / no exceptions! (and equivalent for `SecondLevelDomainRep`) – Cel Jun 12 '12 at 09:24