我想創建一個包含這兩個物體類關系的資料庫表。遷移后我看不到關系表,只有我的資料庫集表。我將分享下面的代碼。
這是一個物體,
public class Server:IEntity
{
[Key]
public int ServerId { get; set; }
public string ServerPassword { get; set; }
// public List<AppUser> UserId { get; set; } do not necessary
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 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
{
[Key]
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中配置一對一或一對多關系時,在資料庫中會在Table中生成一個外鍵,我們可以用它來查找相關物體,而不是生成連接表。但是如果我們配置多對多關系,它可以生成連接表。
例如:
public class Student
{
public int StudentId { get; set; }
public string Name { get; set; }
public IList<StudentCourse> StudentCourses { get; set; }
}
public class Course
{
public int CourseId { get; set; }
public string CourseName { get; set; }
public string Description { get; set; }
public IList<StudentCourse> StudentCourses { get; set; }
}
public class StudentCourse
{
public 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/qianduan/416082.html
標籤:
