在EF中,我需要描述以下关系:
一家公司可能有很多地点,比如
headquarter <= main location
plant ----+
warehouse |
store-1 +----> child Locations
store-2 |
store-n ----+所以我需要一个位置模型中的mainLocationID,这样我就可以
1)给定主位置,我可以访问它的所有子位置
2)给定一个孩子的位置,我可以找到它的主要位置。
所以我试着做了以下几件事:
public class Location
{
public int id { get; set; }
public string name { get; set; }
public string type { get; set; }
public bool flagMainLocation { get; set; }
public int? mainLocationID { get; set; }
public virtual ICollection<Location> ChildLocations { get; set; }
}在我的db上下文中
public class myappContext : DbContext
{
public myappContext() : base("myappContext")
{
}
public DbSet<Location> Locations { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Location>()
.HasOptional(l => l.ChildLocations)
.WithMany()
.HasForeignKey(l => l.mainLocationID);
}
}现在我陷入困境,因为当我试图为Location类搭建一个控制器时,我会得到以下错误
"myapp.DAL.Location_ChildLocations:: Multiplicity conflicts with
the referential constraint in Role 'Location_ChildLocations_Target'
in relationship 'Location_ChildLocations'. Because all of the
properties in the Dependant Role are non-nullable, multiplicity
of the Principal Role must be '1'."我对EF不够精通,无法解密这条错误信息。有人能告诉我这种配置有什么问题吗?
我也希望能以这种方式获得主要位置。
Location myChildLocation = db.Locations.Find(some_location_id);
Location mainLocation = myChildLocation.mainLocation;发布于 2014-06-05 21:00:16
如果你试一试:
modelBuilder.Entity<Location>()
.HasMany(l => l.ChildLocations)
.WithOptional()
.HasForeignKey(l => l.mainLocationID);发布于 2014-06-06 04:25:27
好的,在BiffBaffBoff的提示下,为了到达主位置,添加了一些语法糖,我终于让它运行了:
public class Location
{
public int id { get; set; }
public string name { get; set; }
public string type { get; set; }
public bool flagMainLocation { get; set; }
public int? mainLocationID { get; set; }
public virtual ICollection<Location> ChildLocations { get; set; }
public virtual Location mainLocation { get; set;}
}
public class myappContext : DbContext
{
public myappContext() : base("myappContext")
{
}
public DbSet<Location> Locations { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Location>()
.HasMany(l => l.ChildLocations)
.WithOptional()
.HasForeignKey(l => l.mainLocationID);
}
}参见github https://github.com/kranz/selfRefModel上的工作示例
https://stackoverflow.com/questions/24070019
复制相似问题