我想創建一個資料庫表,其中包括這兩個物體類的關系。遷移后,我看不到關系表,只有我的資料庫集表。我將分享下面的代碼。
這是一個物體,
public class Server: IEntity
{
[Key] 。
public int ServerId { get; set; }
public string ServerPassword { get; set; }
// public List<AppUser> UserId { get; set; } 不用了。
public string ServerName { get; set; }
public DateTime ModifiedDate { get; set; }
public DateTime CreateDate { get; set; }
而這是另一種情況
public class Project: IEntity
{
public string ProjectName { get; set; }
public int ProjectId { get; set; }
public int ServerId { get; set; }
public virtual Server 服務器 { get; set; }
和我的Dbset類
public class AppIdentityDbContext : IdentityDbContext<AppUser,AppRole,string>。
{
public AppIdentityDbContext(DbContextOptions<AppIdentityDbContext> options) : base(options)。
{
}
public DbSet<Server> Servers { get; set; }
public DbSet<Project> Projects { get; set; }
uj5u.com熱心網友回復:
如果你的物體有一對多的關系,你必須把專案的ICollection串列添加到服務器中:
public class Servers: IEntity
{
[] 。
public int ServerId { get; set; }。
...
public virtual ICollection< Projects> Projects{ get; set; }
那么以最簡單的方式,你可以在DbContext中通過覆寫OnModelCreating來配置關系:
public class MyContext : DbContext
{
public DbSet<Servers> Servers { get; set; }
public DbSet< Projects> Projects { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)。
{
modelBuilder.Entity<Projects>()
.HasOne(p => p.Server)
.WithMany(b => b.Projects)。
}
}
uj5u.com熱心網友回復:
一般來說,當我們在Entity Framework或Entity Framework Core中配置一對一或一對多的關系時,在資料庫中,它將在表中生成一個外鍵,我們可以用它來查找相關的物體,而不是生成連接表。但是如果我們配置了多對多的關系,它就可以生成連接表。
例如:
public class Student
{
public int StudentId { get; set; }
public string Name { get; set; }
public IList<StudentCourse> StudentCourses { get; set; }
}
public class Coursepublic int CourseId { get; set; }
public string CourseName { get; set; }
public string Description { get; set; }
public IList<StudentCourse> StudentCourses { get; set; }
}
public class StudentCoursepublic int StudentId { get; set; }
public Student Student { get; set; }
public int CourseId { get; set; }
public Course Course { get; set; }
表的結構:
在 Entity Framework Core 中配置多對多的關系
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/320358.html
標籤:

