EF代码优先映射混淆

时间:2014-07-09 21:32:35

标签: c# entity-framework ef-code-first mapping

我正在使用 Entity Framework Fluent API 执行代码优先方法映射配置,因为我遇到了一些令人困惑的情况。

我的模型和映射配置

我有两个课程:组织课程

public class Organisation {
    public int Id { get; set; }
    public virtual ICollection<Course> Courses { get; set; }
}

public class Course {
    public int Id { get; set; }
    public int OrganisationId { get; set; }
}

我的映射配置如下:

public class OrganisationSchema : EntityTypeConfiguration<Organisation>
{
    public OrganisationSchema()
    {
        ToTable(typeof(Organisation).Name);
        HasKey(x => x.Id);
        HasMany(x => x.Courses).WithRequired(x => x.Organisation).HasForeignKey(x => x.OrganisationId);
    }
}

public class CourseSchema : EntityTypeConfiguration<Course>
{
    public CourseSchema()
    {
        ToTable(typeof(Course).Name);
        HasKey(x => x.Id);
        HasRequired(x => x.Organisation).WithMany(x => x.Courses).HasForeignKey(x => x.OrganisationId);
    }
}

我的目标

我的模型的目标是拥有一个包含许多课程的组织,而课程只有一个组织。

此外,如果我删除组织,我希望EF删除所有相关的课程。但是,如果我删除课程,则不应删除任何组织。

问题

  1. 现在,在我的映射配置中,我明确告诉一个组织有很多课程并指出外键。然后我在一个课程中讲述完全相同的内容,反之亦然。 这种双向映射是否真的不必要,或者我可以跳过其中一个方面吗? EF了解我的目标需要多少映射配置?我真的不想吹我的代码,也不想吹我的头。

  2. 根据我的目标,我需要一些实体删除处理。我知道这是使用WillCascadeOnDelete()扩展名配置的,但我不明白这个扩展名。 我应该在映射配置中设置WillCascadeOnDelete()扩展名;哪一方 - 或两者兼而有之?它是如何影响的?什么是布尔参数值告诉?

1 个答案:

答案 0 :(得分:1)

public class Organisation {
public int Id { get; set; }
public virtual ICollection<Course> Courses { get; set; }
}

public class Course {
    public int Id { get; set; }
    public virtual Organisation Organisation { get; set; }
}



 public class OrganisationSchema : EntityTypeConfiguration<Organisation>
{
    public OrganisationSchema()
    {
        ToTable(typeof(Organisation).Name);            
        HasMany(x => x.Courses).WithRequired(x => .Organisation).WillCascadeOnDelete();
    }
}

我认为上述配置应该适合您的要求。它使用一些约定来定义外键并将映射配置保持在最低限度。

相关问题