我一直在尝试使用EF Code First为我正在处理的项目创建和管理我的数据库。但是,我遇到了一个小问题。
public class Planet
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Required]
public string Planet_Name { get; set; }
[Required]
public int Planet_X { get; set; }
[Required]
public int Planet_Y { get; set; }
[Required]
public string Planet_Desc { get; set; }
public virtual ICollection<Mineral> Minerals { get; set;}
}
public partial class Mineral
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Symbol { get; set; }
[Required]
public string Mineral_Desc { get; set; }
[Required]
public int rate { get; set; }
[Required]
public decimal ratio { get; set; }
}
使用上述内容时,Mineral表获取Planet_Id列集作为ForeignKey。当然,当2个行星具有相同的矿物质时,这会产生导致错误的副作用。我需要的是允许多个行星共享矿物。虽然星球需要知道它有什么矿物质,但矿物质没有理由知道它是什么行星。
因此,我的问题是,我该如何做呢? (注意:我试图将一个公共虚拟行星添加到Mineral类中,它什么都没改变。)
答案 0 :(得分:1)
您需要在ICollection<Planet> Planets
课程中添加Mineral
:
public class Mineral
{
public Mineral()
{
Planets = new HashSet<Planet>();
}
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Symbol { get; set; }
[Required]
public string Mineral_Desc { get; set; }
[Required]
public int rate { get; set; }
[Required]
public decimal ratio { get; set; }
public virtual ICollection<Planet> Planets { get; set; }
}
同样在Planet
课程中,您应该添加默认构造函数:
public class Planet
{
public Planet()
{
Minerals = new HashSet<Mineral>();
}
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Required]
public string Planet_Name { get; set; }
[Required]
public int Planet_X { get; set; }
[Required]
public int Planet_Y { get; set; }
[Required]
public string Planet_Desc { get; set; }
public virtual ICollection<Mineral> Minerals { get; set; }
}
因此,在您的DbContext中,您需要定义实体Planet
和Mineral
,并通过覆盖OnModelCreating
函数创建多对多关系:
public class PlanetContext : DbContext
{
public DbSet<Planet> Peoples { get; set; }
public DbSet<Mineral> Minerals { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Planet>()
.HasMany(p => p.Minerals)
.WithMany(m => m.Planets)
.Map(t => t.MapLeftKey("PlanetID")
.MapRightKey("MineralID")
.ToTable("PlanetMineral"));
}
}