【发布时间】:2018-07-04 06:27:52
【问题描述】:
我正在将我的 ASP.NET MVC 项目更改为带有 Entity Framework Core 和 Fluent API 的 ASP.NET Core MVC。当我尝试配置一对一和一对多关系时,它会在依赖表中生成重复的外键列。
例如:我在上下文的OnModelCreating 方法中有这个:
builder.Entity<Session>()
.HasKey(s=>s.Id);
builder.Entity<Session>()
.Property(s=>s.CourseId)
.IsRequired();
builder.Entity<Session>()
.HasOne<Course>()
.WithMany(c => c.Sessions)
.HasForeignKey(s=>s.CourseId)
.IsRequired();
会话模型是这样的:
public class Session
{
public int Id { get; set; }
// foreign key
public int CourseId { get; set; }
// navigation properties
public virtual Course Course { get; set; }
}
课程模式是这样的:
public class Course
{
public int Id { get; set; }
// Navigation properties
public ICollection<Session> Sessions { get; set; }
}
而不是在迁移中恢复:
modelBuilder.Entity("Blackboard.Models.DomainModels.Session", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("CourseId");
b.HasKey("Id");
b.HasIndex("CourseId");
b.ToTable("Sessions");
});
我明白了:
modelBuilder.Entity("Blackboard.Models.DomainModels.Session", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("CourseId");
b.Property<int?>("CourseId1");
b.HasKey("Id");
b.HasIndex("CourseId");
b.HasIndex("CourseId1");
b.ToTable("Sessions");
});
因此,即使我为关系添加了.IsRequired();,但关系似乎是可选的,并且在表中添加了可选的CourseId1。
该应用程序是在 Mac OSX 上使用 Visual Studio for Mac 开发的。
我已经配置了这么久,我只找到了 Entity Framework 而不是 Entity Framework Core 的东西。他们两个的配置方式不同。有人可以帮帮我吗?
谢谢。
【问题讨论】:
标签: c# asp.net-core-mvc entity-framework-core ef-fluent-api entity-framework-core-migrations