所以,我有件衣服:
public class Garment
{
public int Id { get; set; }
public string Slug { get; set; }
public Kit Kit { get; set; }
public IList<Path> Paths { get; set; }
}和字体:
public class Font
{
public int Id { get; set; }
public string Name { get; set; }
public string Slug { get; set; }
public IList<Garment> Garments { get; set; }
}一个服装可以有一个字体和字体将有0到许多服装。我试着用EF来弥补这个问题:
// Map the GarmentFonts table
modelBuilder.Entity<Font>()
.HasMany(m => m.Garments)
.WithMany()
.Map(m =>
{
m.MapLeftKey("FontId");
m.MapRightKey("GarmentId");
m.ToTable("GarmentFonts");
});但这使得FontId和GarmentId都成为了主要的关键。实际上,我认为它应该只使用GarmentId作为阻止系统的主要键,允许一件衣服使用多个字体。有人知道我怎样才能设置EF来适应我的情况吗?
发布于 2015-05-08 14:16:19
你需要这样的东西:
public class Garment {
public int Id { get; set; }
public string Slug { get; set; }
public Kit Kit { get; set; }
public IList<Path> Paths { get; set; }
public Font Font {get; set;}
}配置如下:
modelBuilder.Entity<Font>()
.HasMany(m => m.Garments)
.WithOptional(y => y.Font);这里不需要链接表。FK在服装桌上。
发布于 2015-05-08 14:33:44
如果您想使用单向导航属性,可以这样配置您的关系:
modelBuilder.Entity<Font>()
.HasMany(f => f.Garments)
.WithOptional();但是,我建议您在Font实体和FK上添加一个Garment导航属性:
public class Garment
{
public int Id { get; set; }
//...
public int? FontId { get; set; }
public Font Font {get; set;}
}配置是这样的:
modelBuilder.Entity<Font>()
.HasMany(f => f.Garments)
.WithOptional(g => g.Font)
.HasForeignKey(g=>g.FontId);发布于 2015-05-08 14:57:37
@octavioccl实际上已经回答了这个问题,但我不喜欢在POCO类中引用FontId,因此我将我的引用改为:
public class Garment
{
public int Id { get; set; }
public string Slug { get; set; }
public Kit Kit { get; set; }
public Font Font { get; set; }
public IList<Path> Paths { get; set; }
}我将字体类保持不变,并在DbContext类中替换了以下内容:
// Map the GarmentFonts table
modelBuilder.Entity<Font>()
.HasMany(m => m.Garments)
.WithMany()
.Map(m =>
{
m.MapLeftKey("FontId");
m.MapRightKey("GarmentId");
m.ToTable("GarmentFonts");
});在这方面:
modelBuilder.Entity<Garment>().HasOptional(m => m.Font).WithMany(m => m.Garments).Map(m => { m.MapKey("FontId"); });就像我说的,这和@actavioccl是一样的,但是不需要在Garment类中指定外键。
https://stackoverflow.com/questions/30125829
复制相似问题