gpt4 book ai didi

c# - 在 Entity Framework 6.1 中添加列 - 多对多 - Code First

转载 作者:太空狗 更新时间:2023-10-29 22:58:18 25 4
gpt4 key购买 nike

举个例子,我在 codeproject 上使用这篇文章中的代码:http://www.codeproject.com/Articles/234606/Creating-a-Many-To-Many-Mapping-Using-Code-First

enter image description here

我试图在我的代码中做一些类似的事情,但我还想要一个数量属性,所以:

  1. 一个类(class)可以有很多人
  2. 一个人可以有很多门类(class)
  3. 每个人都可以选择每门类(class)的数量。 (我知道两次选择相同的类(class)没有意义,但这只是一个例子,或者用汉堡包类型替换类(class):-))

我想我必须在 PersonCourses 表中添加一个名为 Quantity 的列,但我不知道如何在 Code First 中执行此操作。

代码:

public class Person
{
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }

public ICollection<Course> CoursesAttending { get; set; }

public Person()
{
CoursesAttending = new HashSet<Course>();
}
}

public class Course
{
public int CourseId { get; set; }
public string Title { get; set; }

public ICollection<Person> Students { get; set; }

public Course()
{
Students = new HashSet<Person>();
}
}

public class SchoolContext : DbContext
{
public DbSet<Course> Courses { get; set; }
public DbSet<Person> People { get; set; }

public SchoolContext()
: base("MyDb")
{
}
}

上下文:

public class SchoolContext : DbContext
{
public DbSet<Course> Courses { get; set; }
public DbSet<Person> People { get; set; }

public SchoolContext()
: base("MyDb")
{
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Course>().
HasMany(c => c.Students).
WithMany(p => p.CoursesAttending).
Map(
m =>
{
m.MapLeftKey("CourseId");
m.MapRightKey("PersonId");
m.ToTable("PersonCourses");
});
}
}

最佳答案

要将列添加到联结表,您需要将其显式映射为实体并创建两个一对多关系:

public class PersonCourse
{
[Key, Column(Order = 0),ForeignKey("Person")]
public int PersonId { get; set; }
[Key, Column(Order = 1),ForeignKey("Course")]
public int CourseId { get; set; }

public Person Person { get; set; }
public Course Course { get; set; }

public int Quantity{ get; set; }
}

public class Person
{
public int PersonId { get; set; }
//...

public ICollection<PersonCourse> CoursesAttending { get; set; }

public Person()
{
CoursesAttending = new HashSet<PersonCourse>();
}
}

public class Course
{
public int CourseId { get; set; }
//...

public ICollection<PersonCourse> Students { get; set; }

public Course()
{
Students = new HashSet<PersonCourse>();
}
}

如果你想使用 Fluent Api 而不是 Data Annotations,你可以使用这些配置:

modelBuilder.Entity<PersonCourse>().HasKey(pc => new { pc.PersonId, pc.CourseId});

modelBuilder.Entity<PersonCourse>().HasRequired(pc=>pc.Person).WithMany(p=>p.CoursesAttending).HasForeignKey(pc=>pc.PersonId);

modelBuilder.Entity<PersonCourse>().HasRequired(pc=>pc.Course).WithMany(c=>c.Students).HasForeignKey(pc=>pc.CourseId);

关于c# - 在 Entity Framework 6.1 中添加列 - 多对多 - Code First,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30964620/

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