【问题标题】:Ef code first with existing databaseEf 代码优先与现有数据库
【发布时间】:2012-04-27 16:37:43
【问题描述】:
假设我有两个数据库表,比如tb1 和tb2,带有
[tb1]
id primary key
name
lastname
[tb2]
id primary key
tb1_ID foreign key
phone_no
degree
grade
关系tb1 可能持有表二的多条记录。即:一对多的关系。
对于这种关系,我需要一个实体来保存 tb1 的所有列,并且在 tb2 上只有一列(只说 ph 号)。
建议我最简单的方法。
【问题讨论】:
标签:
asp.net
asp.net-mvc-3
entity-framework
asp.net-mvc-2
entity-framework-4
【解决方案1】:
最简单的方法 - 创建数据库视图并将其映射为新实体。更好但更复杂的方法 - 直接映射这些表并在 LINQ 查询中使用投影到您的自定义类型:
var data = context.TB2s.Select(t => new TBViewModel
{
Id = t.TB1.Id,
Name = t.TB1.Name,
LastName = t.TB1.LastName,
PhoneNumber = t.PhoneNumber
});
【解决方案2】:
不知道它是否正常工作
试试看
Public class tb1
{
public int id{get; set;}
public string name{get; set;}
public string lastName{get; set;}
[NotMapped]
public List<string> relatedPhoneNo{get; set;}
}
var data = db.master.Select(t1 => new tb1
{
id = t1.id,
name = t1.name,
lastName = t1.lastName,
relatedPhoneNo= (from t2 in db.tb2
where t2.id==t.id
select t2.city ).ToList()
});
【解决方案3】:
您是否真的有一个包含数据的现有数据库,或者您只是希望 EF Code First 生成一个看起来像现有数据库设计的数据库?
如果您在 MVC3 模型中创建两个单独的类,EF 可以创建一个看起来像这样的数据库(假设您正在根据标签执行 MVC3)。
这是一个使用学生和课程的示例:
public class Student
{
public int Id { get; set; }
public string Name{ get; set; }
//This should make the 1 to many relationship to the second table
public List<Course> Courses { get; set; }
}
public class Course
{
public int Id { get; set; }
public string CourseName{ get; set; }
}
在这种情况下,EF Code First 将创建一个与表 Courses 具有一对多关系的表 Student。
生成的数据库如下所示:
[Student]
id primary key
name
[Courses]
id primary key
CourseName
Student_ID foreign key