【发布时间】:2017-01-19 23:01:57
【问题描述】:
我正在使用实体框架,并且我使用联结表建立了多对多关系。
据我了解,它应该生成,所以我的上下文如下所示:
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; }
}
}
Entity Framework 生成了一些默认的联结表名称,因此我认为我需要定义该名称。这就是问题所在,如何做到这一点?
编辑:
我已经添加了fluent api;
可以看到属性:
public ICollection<SkillSet> SkillSets { get; set; }
但是当我尝试例如:
var ca = this._catalog.Candidates.FirstOrDefault(x => x.id == 125).SkillSets;
我得到 0 好像集合从未被填满,我仔细检查了数据库关系。
【问题讨论】:
-
看看这个question。我认为它会帮助你,我认为它是相同的情况
标签: c# entity-framework