【发布时间】:2014-09-03 19:17:37
【问题描述】:
不知道有没有办法 提前将数据库优先方法与手动生成的类(模型)一起使用(就像代码优先方法一样), 但不使用实体框架使用数据库优先方法创建的自动生成代码? 我有 3 个班级(其中前两个学生和课程有多对多关系),代表模型: 第一个是学生:
public class Student
{
public int StudentID { get; set;}
public string Name { get; set;}
public DateTime BirthDate { get; set;}
public ICollection<StudentToCourse> StudentToCourses { get; set; }
public Student()
{
StudentToCourses = new List<StudentToCourse>();
}
}
然后课程:
public class Course
{
public int CourseID { get; set; }
public string CourseName { get; set; }
public ICollection<StudentToCourse> StudentToCourses { get; set; }
public Course()
{
StudentToCourses = new List<StudentToCourse>();
}
}
以及具有附加属性 StudentToCourse 的关系/中间类:
public class StudentToCourse
{
[Key, Column(Order = 0)]
public int StudentID { get; set; }
[Key, Column(Order = 1)]
public int CourseID { get; set; }
[Key, Column(Order = 2)]
public DateTime Date { get; set; }
public virtual Student Student { get; set; }
public virtual Course Course { get; set; }
//public ICollection<Student> Students { get; set; }
//public ICollection<Course> Courses { get; set; }
public int Grade { get; set; }
}
另外,我使用 VS 2013 中的 LocalDb 功能创建了数据库
我有 3 张桌子: 课程:
CREATE TABLE [dbo].[Courses]
(
[CourseID] INT NOT NULL PRIMARY KEY IDENTITY,
[CourseName] NVARCHAR(100) NOT NULL,
)
学生:
CREATE TABLE [dbo].[Students]
(
[StudentID] INT NOT NULL PRIMARY KEY IDENTITY,
[Name] NVARCHAR(50) NOT NULL,
[BirthDate] DATETIME NOT NULL,
)
StudentToCourses 关系表:
CREATE TABLE [dbo].[StudentsToCourses]
(
[StudentID] INT REFERENCES Students(StudentID) NOT NULL,
[CourseID] INT REFERENCES Courses(CourseID) NOT NULL,
[Date] DATETIME NOT NULL,
[Grade] INT NOT NULL,
PRIMARY KEY (StudentID, CourseID, Date)
)
不幸的是,我对这种方法没有运气,我确实获得了学生的数据,但我没有从关系表中收到数据,而且我无法收到每个学生的所有相关成绩。
我在 google 和 stackoverflow 中搜索了相关主题,但所有这些主题对我都没有帮助,尽管我在 topic 中找到了上面的示例。
【问题讨论】:
-
为什么 Code First 不适合你?
-
可以,但是为什么呢?
-
是的,它可以做到,但真正的问题是为什么? Database-First 允许 EF 确保一切正常。 Code-First 要求您深入了解您的对象图并相应地创建所有内容。混合根本不是一个好主意,一个原因是因为更改实际上需要更多的工作,而不是任何一个默认值。这很可能是XY Problem,即你认为这个你无法工作的解决方案将解决根本问题,但你没有描述根本问题。
-
我想尽可能的简化它,我也想完全控制数据库。
-
你要求的并不简单。您可以使用 Database-First 和 Code-First 完全控制数据库。 What if My Database Changes - Code First: If your database schema changes you can either manually edit the classes or perform another reverse engineer to overwrite the classes.
标签: c# sql entity-framework