我正在使用实体框架,并且我有一个使用连接表的多对多关系。
据我所知,它应该被生成,所以我的上下文看起来像这样:
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,好像集合从来没有填满过一样,我仔细检查了一下DB关系是否存在。
发布于 2017-01-19 21:56:17
您需要使用FluentAPI,如下所示:
型号:
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; }
}FluentAPI
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");
}https://stackoverflow.com/questions/41743139
复制相似问题