NET 3.5 SP1中的Entity Framework着重于“数据库优先(Database First)”,即从数据库中逆工程生成实体数据模型。而Visual Studio 2010/.NET 4.0中的Entity Framework 4.0引进了“模 型优先(Model First)”,即允许你先生成实体数据模型,然后生成映射到该模型的数据库。而Entity Framework Feature CTP1版则更进一步,推出了“只用代码(Code Only)”的预览版,不再需要EDMX文件
- Visual Studio 2010 Beta 1
- Entity Framework Feature CTP1 (同时参考Entity Framework Feature CTP 1一文,如果你对该CTP中其他特性,特别是POCO模板等,感兴趣的话)
- 本地的SQL Server 2008 Express或者SQL Server
Code Only全程示范many to many Relationships
1、Database
2、Map 到Entity
(1)course Entity
public class Course : IEntity
{
private readonly ICollection<CourseCategory> _courseCategorys;
public Course()
{
_courseCategorys = new List<CourseCategory>();
}
public virtual ICollection<CourseCategory> CourseCategorys
{
[DebuggerStepThrough]
get { return _courseCategorys; }
}
public virtual DateTime ModifiedDate { get; set; }
public virtual DateTime CreatedDate { get; set; }
public virtual string Title { get; set; }
}
(2)CourseCategory
public class CourseCategory : IEntity
{
private readonly ICollection<Course> _courses;
public CourseCategory()
{
_courses = new List<Course>();
}
public virtual string Title { get; set; }
public virtual string Description { get; set; }
public virtual DateTime ModifiedDate { get; set; }
public virtual DateTime CreatedDate { get; set; }
}
注:这里的CourseInCategory只是存放2者之间的关系,那么不需要map到Entity中
3、Configuration
(1)Course
public class CourseConfiguration : EntityConfiguration<Course>
{
public CourseConfiguration()
{
HasKey(c => c.Id);
Property(c => c.Id).IsIdentity();
Property(c => c.ModifiedDate);
Property(c => c.CreatedDate);
Property(c => c.Title).IsUnicode().IsRequired().HasMaxLength(50);
MapSingleType(c => new
{
CourseID = c.Id,
c.CreatedDate,
c.Description,
c.ModifiedDate,
c.Title,
}).ToTable("Course");
}
}
(2)CourseCategory
public class CourseCategoryConfiguration : EntityConfiguration<CourseCategory>
{
public CourseCategoryConfiguration()
{
HasKey(cc => cc.Id);
Property(cc => cc.Id).IsIdentity();
Property(cc => cc.Title).HasMaxLength(50).IsUnicode().IsRequired();
Property(cc => cc.Description).HasMaxLength(250).IsUnicode().IsRequired();
Property(cc => cc.CreatedDate);
Property(cc => cc.EducationId);
Property(cc => cc.ModifiedDate);
Relationship(cc => cc.Courses).FromProperty(c => c.CourseCategorys).Map("CourseInCategory", (cc, c) => new { CourseID = c.Id, CategoryID = cc.Id });
MapSingleType(cc => new
{
CategoryID = cc.Id,
cc.Title,
cc.Description,
cc.CreatedDate,
cc.EducationId,
cc.ModifiedDate,
cc.ParentCategoryId,
}).ToTable("CourseCategory");
}
}