gpt4 book ai didi

c# - 更改 Entity Framework 6 中的默认联结表名

转载 作者:行者123 更新时间:2023-11-30 17:34:59 25 4
gpt4 key购买 nike

我正在使用 Entity Framework ,并且使用联结表建立多对多关系。

据我所知,应该生成它以便我的上下文看起来像这样:

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,好像集合从未被填满,我仔细检查了数据库关系是否存在。

最佳答案

您需要像这样使用 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; }
}

流利的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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com