I have the following entities:
public interface IMyEntity
{
[Key]
int Id { get; set; }
IMyDetail MyDetail { get; set; }
ICollection
After several sleepless nights I believe I have found a solution to this problem. I have tested this approach (a little) and it seems to work but it probably needs some more eyeballs to tear it apart and explain why this approach might break. I used FluentAPI to set up my database attributes instead of decorating the entity class properties. I've removed the virtual attribute from the entity class members (i prefer to use explicit includes instead of falling back on lazy loading for child entities). I've also renamed the example classes and properties a bit so that it is clearer to me. I'm assuming you are trying to express a one-to-many relationship between an entity and its details. You are trying to implement interfaces for your entities in the repository tier so that upper tiers are agnostic to the entity classes. Higher tiers are only aware of the interfaces not the entities themselves...
public interface IMyEntity
{
int EntityId { get; set; }
//children
ICollection Details { get; set; }
}
public interface IMyDetailEntity
{
int DetailEntityId { get; set; }
int EntityId { get; set; }
int IntValue { get; set; }
//parent
IEntity Entity { get; set; }
}
public class MyEntity : IMyEntity
{
public int EntityId { get; set; }
private ICollection _Details;
public ICollection Details {
get
{
if (_Details == null)
{
return null;
}
return _Details.Select(x => (MyDetailEntity) x).ToList();
}
set
{
_Details = value.Select(x => (IMyDetailEntity) x).ToList();
}
}
ICollection IMyEntity.Details
{
get
{
return _Details;
}
set
{
_Details = value;
}
}
}
public class MyDetailEntity : IMyDetailEntity
{
public int DetailEntityId { get; set; }
public int EntityId { get; set; }
public int IntValue { get; set; }
private IMyEntity _Entity;
public MyEntity Entity
{
get
{
return (Entity)_Entity;
}
set
{
_Entity = (Entity)value;
}
}
IEntity IMyDetailEntity.Entity
{
get
{
return _Entity;
}
set
{
_Entity = value;
}
}
}