Entity Framework 小知识(五)

多对多关系映射 中关联表是EF自动生成的。但有时候我们需要显示定义关联表。我们可以按照如下步骤定义(继续使用多对多关系映射这篇文章饿代码):

  1. 定义关联表类:
public class StudentCourses : BaseEntity
{
    public int StudentId { get; set; }
    public virtual Student Student { get; set; }
    public int CourseId { get; set; }
    public virtual Course Course { get; set; }
}
  1. 修改 StudentCourses 类中的导航属性:
public class Student:BaseEntity
{
    public string Name { get; set; }
    public int Age { get; set; }
    public virtual ICollection<StudentCourses> StudentCourses { get; set; }
}

public class Course : BaseEntity
{
    public string Name { get; set; }
    public string TeacherName { get; set; }
    public virtual ICollection<StudentCourses> StudentCourses { get; set; }
}
  1. 修改 StudentMapCoursesMap 映射:
public class StudentsMap : EntityTypeConfiguration<Student>
{
    public StudentsMap()
    {
        //表名称
        ToTable("Students");
        //主键
        HasKey(p => p.Id);

        //设置主键自增长
        Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        //设置要映射的数据
        Property(p => p.Name).HasColumnType("VARCHAR").HasMaxLength(50);
        Property(p => p.Age);
        Property(p => p.CreateDateTime);

        //设置关系
        HasMany(p => p.StudentCourses)
            .WithRequired(p => p.Student)
            .HasForeignKey(p => p.StudentId);

    }
}

public class CourseMap : EntityTypeConfiguration<Course>
{
    public CourseMap()
    {
        ToTable("Coureses");
        HasKey(p => p.Id);
        Property(p => p.Id)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        Property(p => p.Name).HasColumnType("VARCHAR").HasMaxLength(50);
        Property(p => p.TeacherName);
        Property(p => p.CreateDateTime);

        HasMany(p => p.StudentCourses)
            .WithRequired(p => p.Course)
            .HasForeignKey(p => p.CourseId);
    }
}

运行代码,查看数据库发现生成了同样的数据库,多对多关系也正确的反映出来。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

喵叔哟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值