我正在使用实体框架,并且使用联结表有很多对很多的关系。

据我了解应该生成它,因此我的上下文如下所示:

public DbSet<Candidate> Candidates { get; set; }
public DbSet<SkillSet> SkillSets { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Candidate>().HasMany(t => t.SkillSets).WithMany(t => t.Candidates)
        .Map(m =>
        {
            m.ToTable("candidate_skillset");
            m.MapLeftKey("candidate_id");
            m.MapRightKey("skillset_id");
        });

        modelBuilder.Entity<SkillSet>().ToTable("skillset");
        modelBuilder.Entity<Candidate>().ToTable("candidate");
    }


候选模型:

namespace CandidateCatalog.Model
{
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

[Table("candidate")]
public class Candidate
{
    #region Simple propertied

    [Key]
    public int id { get; set; }

    [Column("firstname")]
    public string Firstname { get; set; }
    #endregion

    #region reference properties

    public int? commendation_id { get; set; }
    [ForeignKey("commendation_id")]
    public Commendation commendation { get; set; }

    public ICollection<SkillSet> SkillSets { get; set; }
    #endregion
}


}

技能集模型:

namespace CandidateCatalog.Model
{
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;

[Table("skillset")]
public class SkillSet : SimpleDictionary
{
    public virtual ICollection<Candidate> Candidates { get; set; }
}
}


实体框架生成了一些默认的联结表名称,因此我想需要定义该名称。这是问题所在,该如何解决?

编辑:

我添加了流利的api;

它可以看到属性:

 public ICollection<SkillSet> SkillSets { get; set; }


但是当我尝试例如:

   var ca = this._catalog.Candidates.FirstOrDefault(x => x.id == 125).SkillSets;


我得到0,好像从未填充过集合,我已经仔细检查了数据库关系。

最佳答案

您需要使用Fluent API,例如:
楷模:

public class Candidate
{
    [Key]
    public int CandidateId { get; set; }

    Column("firstname")]
    public string Firstname { get; set; }


    public virtual ICollection<SkillSet> SkillSets { get; set; }
}



public class SkillSet : SimpleDictionary
{
    [Key]
    public int SkillSetId { get; set; }

    public virtual ICollection<Candidate> Candidates { get; set; }
}

流利的API
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{

    modelBuilder.Entity<SkillSet>()
                .HasMany<Candidate>(s => s.Candidates)
                .WithMany(c => c.SkillSets)
                .Map(cs =>
                {
                    cs.MapLeftKey("SkillSetId");
                    cs.MapRightKey("CandidateId");
                    cs.ToTable("candidate_skillset");
                });
    modelBuilder.Entity<SkillSet>().ToTable("skillset");
    modelBuilder.Entity<Candidate>().ToTable("candidate");
}

关于c# - 在 Entity Framework 6中更改默认联结表名,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41743139/

10-12 04:19