I have the following entities:
public interface IMyEntity
{
[Key]
int Id { get; set; }
IMyDetail MyDetail { get; set; }
ICollection<IMyDetail> CollectionOfReferences { get; set; }
}
public interface IMyDetail
{
[Key]
int Id { get; set; }
int IntValue { get; set; }
}
public class MyEntity : IMyEntity
{
[Key]
public virtual int Id { get; set; }
public virtual IMyDetail MyDetail { get; set; }
public virtual ICollection<IMyDetail> CollectionOfReferences { get; set; }
}
public class MyDetail : IMyDetail
{
[Key]
public virtual int Id { get; set; }
public virtual int IntValue { get; set; }
}
I want to use EF CodeFirst to access the database and to create database schema. But CodeFirst doesn't allow to use interface types for relations between entities. Therefore it doesn't create relation between MyEntity and MyDetail. I can't change interfaces therefore I can't change the type of property to MyDetail instead of IMyDetail. But I know that the client of this model will use only one implementation of each interface.
I've found a workaround for properties of type IMyDetail. I can create a property of type MyDetail and explicitly implement property of interface:
private MyDetail _myDetail;
public virtual MyDetail MyDetail
{
get
{
return this._myDetail;
}
set
{
this._myDetail = value;
}
}
IMyDetail IMyEntity.MyDetail
{
get
{
return this._myDetail;
}
set
{
this._myDetail = (MyDetail)value;
}
}
It works fine. But this solution doesn't work with ICollection<IMyDetail>
because I can't cast it to ICollection<MyDetail>
.
Are there any solutions for this?
See Question&Answers more detail:os