【发布时间】:2019-05-01 05:54:13
【问题描述】:
我要使用这个界面:
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();
}
}
}
这个实现阻止我从集合中删除一个元素:
IFoo iFoo = MyIFooFactory.CreateIFoo();
IBar iBar = iFooIBars.First();
iFoo.IBars.Remove(iBar);
这不会删除元素!我明白为什么。原因是我的接口集合getter,又是这样:
public ICollection<IBar> IBars
{
get
{
return Bars.Cast<IBar>().ToList();
//or return new List<ICardInquiry>(CardsInquiries);
}
...
}
IBars 返回一个新列表,因此该元素将从返回的列表中删除,而不是从原始集合 (Bars) 中删除。
我怎样才能摆脱这种情况? 我真的不想让 IFoo 知道 Bar 并且只操纵 IBar。
【问题讨论】:
-
任何理由
Bars不能只是ICollection<IBar>? -
@Loocid : Bar 和 Foo 是实体框架模型类。如果我将 IBars 声明为 ICollection
而不是 ICollection ,EF 将不会根据数据库人口设置我的导航属性。
标签: c# collections interface