假设我有两个数据库表,说tb1
和tb2
,与
Ef中的代码先用现有的数据库
[tb1]
id primary key
name
lastname
[tb2]
id primary key
tb1_ID foreign key
phone_no
degree
grade
关系tb1
可容纳表两个多记录。即:一对多的关系。
对于这种关系,我需要一个实体,它保存tb1
的所有列,并且在tb2
(也就是唯一的编号)上只有一列。
建议将最简单的方式推荐。
假设我有两个数据库表,说tb1
和tb2
,与
Ef中的代码先用现有的数据库
[tb1]
id primary key
name
lastname
[tb2]
id primary key
tb1_ID foreign key
phone_no
degree
grade
关系tb1
可容纳表两个多记录。即:一对多的关系。
对于这种关系,我需要一个实体,它保存tb1
的所有列,并且在tb2
(也就是唯一的编号)上只有一列。
建议将最简单的方式推荐。
不知道,如果它的正确与否
工作试试看
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()
});
最简单的方法 - 创建数据库视图并将其映射为新实体。的更好,但更复杂的方式 - 直接映射这些表并使用投影在LINQ查询到您的自定义类型:
var data = context.TB2s.Select(t => new TBViewModel
{
Id = t.TB1.Id,
Name = t.TB1.Name,
LastName = t.TB1.LastName,
PhoneNumber = t.PhoneNumber
});
你真的有数据的现有数据库,或者你只是想EF代码首先生成一个数据库那看起来就像现有的数据库设计?
如果您只是在MVC3模型中创建两个单独的类(假设您正在根据您的标记执行MVC3),EF可以创建一个看起来像这样的数据库。
下面是使用学生和课程的例子:
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代码首先要创建一个具有1台学生用表课程一对多的关系。
产生的数据库是这样的:
[Student]
id primary key
name
[Courses]
id primary key
CourseName
Student_ID foreign key
你的代码是一个一个映射,但我需要一对多的东西 – RollerCosta 2012-04-16 11:03:22
我编辑了代码以支持一对多关系。 – 2012-04-16 11:24:56