简体   繁体   English

实体框架中的映射

[英]Mapping in Entity Framework

I have an existing DB schema like this (cant change it ..) . 我有一个这样的现有数据库模式(不能更改..)。 I need to do a EF mapping 我需要做一个EF映射

Student table: Student桌:

ID    Name     CourseID
------------------------
 1    Name1     100023
 2    Name2     100023
 3    Name3     100024  
 4    Name4     NULL  

Course table: Course表:

ID   CourseID   CourseName
--------------------------
 1   100023      Course1  
 2   100022      Course2  
 3   100024      Course3  
 4   100023      Course1  

ID is the primary key in both the tables. ID是两个表中的主键。 CourseID is the column for the relationships. CourseID是关系的列。

There is no explicit relationship in the database (SQL Server) also. 数据库(SQL Server)中也没有明确的关系。

When I try to do a mapping in EF by specifying CourseID as the key required to do the mapping it throws up an error telling it is not defined as the key property. 当我尝试通过指定CourseID作为执行映射所需的键来尝试在EF中进行映射时,它抛出一条错误消息,告知未将其定义为键属性。 I cannot add it as the Key property as it is a null-able field. 我不能将其添加为Key属性,因为它是可空字段。

Is there any way I could do this mapping? 有什么办法可以做这个映射吗?

That's a pretty rough schema to work with. 这是一个非常粗糙的架构。 However, you might be able to use a composite key for the courses table. 但是,您可能可以对courses表使用复合键。 I haven't tested it, but something like this should work. 我还没有测试过,但是类似的东西应该可以工作。

public class Course
{
    [Key, Column(Order = 0)]
    public int ID { get; set; }

    [Key, Column(Order = 1)]
    public int? CourseID { get; set; }

    public string CourseName { get; set; }
}

public class Student
{
    [Key]
    public int ID { get; set; }

    public string Name { get; set; }

    public int? CourseID { get; set; }

    [ForeignKey("CourseID")]
    public Course Course { get; set; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM