我实现了基于接口的体系结构,因此我的业务层可以具有几种模型实现。
public interface IFoo
{
int Id { get; set; }
string Name { get; set; }
ICollection<IBar> IBars{ get; set; } //association with another entity
}
public class Foo : IFoo
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Bar> Bars{ get; set; }
//Interface implementation
public ICollection<IBar> IBars
{
get
{
return Bars.Cast<IBar>().ToList();
//or return new List<ICardInquiry>(CardsInquiries);
}
set
{
if (value is ICollection<IBar>)
Bars= ((ICollection<IBar>)value).Cast<Bar>().ToList();
else
throw new NotImplementedException();
}
}
}
在我的上下文中,我将拥有这个:
public interface IMy_Context : IDisposable
{
IList<IFoo> IFoos { get; }
IList<IBar> IBars { get; }
}
...
public class My_Context : DbContext, IMy_Context
{
public DbSet<Bar> Bars{ get; set; }
public DbSet<Foo> Foos{ get; set; }
//interface implementations
public IList<IFoo> IFoos
{
get
{
return Foos.ToList().Cast<IFoo>().ToList();
}
}
public IList<IUser> IBars
{
get
{
return Bars.ToList().Cast<IBar>().ToList();
}
}
}
那很好。 但是...如果要从集合中删除元素,则会遇到问题:
IFoo iFoo = ...;
IBar iBar = iFoo.IBars.First(b=> ...);
iFoo.Remove(iBar)
这不会删除元素! 我知道为什么。 原因是我的接口集合获取器,再次如下:
public ICollection<IBar> IBars
{
get
{
return Bars.Cast<IBar>().ToList();
//or return new List<ICardInquiry>(CardsInquiries);
}
...
}
IBars返回一个新列表,因此该元素将从返回列表中删除,而不是从原始Model集合(Bars)中删除。
如何解决这种情况并保留接口DAL实现?