繁体   English   中英

实体框架 - 代码优先 - 允许多个实体引用单个实体

[英]Entity Framework - Code First - Allowing Multiple Entities to reference a single entity

我一直在尝试使用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类中,它什么都没改变。)

你需要在Mineral类中添加一个ICollection<Planet> Planets

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中,你需要定义实体PlanetMineral并通过覆盖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"));
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM