我最近开始使用EF和Code First,并且遇到了这个让我感到困惑的问题。我将非常感谢有关此主题的任何反馈,这将有助于我解决上述问题。
请考虑以下示例....
public class SomeType
{
public SomeType()
{
Properties = new List<BaseProperty>();
}
public int PrimaryKey { get; set; }
public string Name { get; set; }
public List<BaseProperty> Properties { get; set; }
}
public abstract class BaseProperty
{
public int PrimaryKey { get; set; }
public string PropertyName { get; set; }
// FK set through Type Configuration File.
public SomeType ParentInstance { get; set; }
}
public class PropertyA : BaseProperty
{
// some unique properties.
}
public class PropertyB : BaseProperty
{
// some unique properties.
}
public class PropertyC : BaseProperty
{
// some unique properties.
}
public class PropertyD : BaseProperty
{
// some unique properties.
}
所有这一切都适用于适当的类型配置类,它们映射到2个表(1表示'SomeType',第二个表示'BaseProperty'以及剩余的派生实体,通过使用鉴别器列)。
现在,由于我无法控制的情况,我被迫将'SomeType'修改成这样的东西....
public class SomeType
{
public SomeType()
{
PropertiesAB = new List<BaseProperty>();
PropertiesC = new List<PropertyC>();
PropertiesD = new List<PropertyD>();
}
public int PrimaryKey { get; set; }
public string Name { get; set; }
public List<BaseProperty> PropertiesAB { get; set; } // collection of PropertyA and PropertyB
public List<PropertyC> PropertiesC { get; set; } // collection of PropertyC
public List<PropertyD> PropertiesD { get; set; } // collection of PropertyD
}
这在NHibernate中使用包很容易,但在使用Code First的EF中是否存在相同的意义?有什么想法吗 ?我不想编写自己的Collection,它将把这些新列表上要执行的所有操作转发和操作到一个主列表,该列表实际上将映射到数据库。
请忽略上面代码中任何缺少的“虚拟”修饰符或其他任何内容,因为它只是一个示例而不是我实际使用的。
谢谢您的回复。
更糟糕的是,你可以这样做:
public class SomeType
{
public SomeType()
{
Properties = new List<BaseProperty>();
}
public int PrimaryKey { get; set; }
public string Name { get; set; }
public List<BaseProperty> Properties { get; set; }
public List<BaseProperty> PropertiesAB
{
get
{
return Properties.Where(p=>p is PropertyA || p is PropertyB);
}
set
{
//Remove all the properties already in the Properties collection of
//the type A and B and then
Properties.AddRange(value)
}
}
//Same with rest of the properties
}
如果在域层之外使用类,也可以将Properties属性设置为internal