我有 2 个实体,每个实体都有一个相关的 c# 类。我在表 A上设置了一个导航属性,以包含对表 B中许多项目的引用。当我创建一个新的表 A 类对象时,我需要能够在表 A中创建表 B对象的集合。如何在表 A c# 类中设置导航属性?
数据模型: http ://bluewolftech.com/mike/mike/datamodel.jpg
我有 2 个实体,每个实体都有一个相关的 c# 类。我在表 A上设置了一个导航属性,以包含对表 B中许多项目的引用。当我创建一个新的表 A 类对象时,我需要能够在表 A中创建表 B对象的集合。如何在表 A c# 类中设置导航属性?
数据模型: http ://bluewolftech.com/mike/mike/datamodel.jpg
导航属性在 EF 中很简单。下面的示例显示了导航属性的外观:
public class Foo
{
public int FooId { get; set; }
public string SomeProperty { get; set; }
public virtual IEnumerable<Bar> Bars { get; set; }
}
其中Foo
代表tableA,Bar
代表tableB。他们导航属性的关键字是虚拟的,默认情况下启用延迟加载。这是假设您使用的是 EF4.1 Code First。
编辑
在我的脑海中,这对你来说应该是一个很好的开始模板:
public class PointOfInterestContext : DbContext
{
public IDbSet<PointOfInterest> PointOfInterest { get; set; }
public IDbSet<POITag> POITag { get; set; }
public IDbSet<Tag> Tag { get; set; }
public override OnModelCreating(DbModelBuilder modelBuilder)
{
// custom mappings go here
base.OnModelCreating(modelBuilder)
}
}
public class PointOfInterest
{
// properties
public int Id { get; set; }
public string Title { get; set; }
// etc...
// navigation properties
public virtual IEnumerable<POITag> POITags { get; set; }
}
public class POITag
{
// properties
public int Id { get; set;}
public int PointOfInterestId { get; set; }
public int TagId { get; set; }
// navigation properties
public virtual PointOfInterest PointOfInterest { get; set; }
public virtual Tag Tag { get; set; }
}
public class Tag
{
// properties
public int Id { get; set; }
public string TagName { get; set; }
// etc...
// navigation properties
public virtual IEnumerable<POITags> POITags { get; set; }
}
然后,您将在业务对象中实现其他逻辑。实体应该是轻量级的,最多应该有数据属性。我更喜欢通过 OnModelCreating 使用流畅的映射。
这里有一些很好的参考:
MSDN - EF 4.1 Code First
Code First Tutorial