gpt4 book ai didi

c# - 首先编码与关系表中属性的多对多关系

转载 作者:太空宇宙 更新时间:2023-11-03 10:38:26 25 4
gpt4 key购买 nike

我想用关系表创建关系属性。以下是引用代码。但是代码创建了 2 个表 BookStudents 和 BookStudents1。其中一个具有没有外键的关系属性,而另一个创建没有属性但具有外键的表。我该如何解决这个问题?

public class BookStudent
{
[Key, Column(Order = 0)]
public int BookID { get; set; }
[Key, Column(Order = 1)]
public int StudentID { get; set; }
public DateTime FromDate { get; set; }
public DateTime ToDate { get; set; }
}


public class Context : DbContext
{
public Context() : base("name=DefaultConnection") { }
public DbSet<Book> Books { get; set; }
public DbSet<Student> Students { get; set; }
public DbSet<BookStudent> BookStudents { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Book>().HasMany<Student>(t => t.Students).WithMany(t => t.Books).Map(t =>
{
t.MapLeftKey("BookId");
t.MapRightKey("StudentId");
t.ToTable("BookStudents");
});
}
}

最佳答案

在代码优先的许多情况下,我们不需要在 OnModelCreating 上明确定义关系。使用下面的代码这将解决您的问题。

public class BookStudent
{
[Key, Column(Order = 0)]
public int BookID { get; set; }
[Key, Column(Order = 1)]
public int StudentID { get; set; }
public DateTime FromDate { get; set; }
public DateTime ToDate { get; set; }

//below two lines will define foreign key
public Student Student { get; set; }
public Book Book { get; set; }
}


public class Context : DbContext
{
public Context() : base("name=DefaultConnection") { }
public DbSet<Book> Books { get; set; }
public DbSet<Student> Students { get; set; }
public DbSet<BookStudent> BookStudents { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//remove below code
//modelBuilder.Entity<Book>().HasMany<Student>(t => t.Students).WithMany(t => t.Books).Map(t =>
//{
// t.MapLeftKey("BookId");
// t.MapRightKey("StudentId");
// t.ToTable("BookStudents");
//});
}
}

关于c# - 首先编码与关系表中属性的多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26511088/

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