I have the following entities:
public interface IMyEntity
{
[Key]
int Id { get; set; }
IMyDetail MyDetail { get; set; }
ICollection
A workaround is to create a special implementation for each interface you want to use with Entity Framework, utilizing the adapter pattern:
// Entity Framework will recognize this because it is a concrete type
public class SecondLevelDomainRep: ISecondLevelDomain
{
private readonly ISecondLevelDomain _adaptee;
// For persisting into database
public SecondLevelDomainRep(ISecondLevelDomain adaptee)
{
_adaptee = adaptee;
}
// For retrieving data out of database
public SecondLevelDomainRep()
{
// Mapping to desired implementation
_adaptee = new SecondLevelDomain();
}
public ISecondLevelDomain Adaptee
{
get { return _adaptee; }
}
public string Id
{
get { return _adaptee.Id; }
set { _adaptee.Id = value; }
}
// ... whatever other members the interface defines
}
// Repositor is your DbContext
public void SubmitDomain(ISecondLevelDomain secondLevelDomain)
{
Repositor.SecondLevelDomainReps.Add(new SecondLevelDomainRep(secondLevelDomain));
Repositor.SaveChanges();
}
public IList RetrieveDomains()
{
return Repositor.SecondLevelDomainReps.Select(i => i.Adaptee).ToList();
}
For more complex interfaces/classes, you may get InvalidOperationException - see Conflicting changes with code first foreign key in Entity Framework for an implementation that works with such object hierarchies