我把他文章翻译了,高手出来点评一下啊:
LINQ to SQL Mapping...I think it could work
这个代码例子是我从Rob Conery's ASP.NET MVC Storefront的视频教学中得来的灵感。这里是一些原因我用这种框架而不是使用NHibernate在这个项目上。
1.我可以随时修改它。。。这就是接口的编程美感
2.LINQ to SQL 真的是太简单了。。。对,我听过。。有人说LINQtoSQL不行了,但是只是不被支持
3.它与其他框架不同,我还没见过类似的框架被成功实现。
4.我和好奇我的方法能不能在程序员社区中抛砖引玉得到其他人的想法。
首先,我建立了我的基本模型,像这样:
接着,我建立我的LINQ to SQL, 像这样:(当然,假设我已经进行过测试了:) )
所以我建立我的ISchoolRepository 像这样:
public interface ISchoolRepository
{
School GetSchoolById(int schoolId);
IQueryable<school> GetAll();
IQueryable<student> GetEnrolledStudentsBy(int schoolId);
}
所以, 这是我对ISchoolRepository接口的implementation:
public class SqlSchoolRepository : ISchoolRepository, IDisposable
{
private readonly LearningDataContext dc;
public SqlSchoolRepository()
{
dc = new LearningDataContext();
}
public Core.Model.School GetSchoolById(int schoolId)
{
return dc.GetSchoolById(schoolId); //EXTENSION METHOD
}
public IQueryable<Core.Model.School> GetAll()
{
return dc.GetAllSchools(); //EXTENSION METHOD
}
Now you see how I have the filters added on too like Rob did in his videos? I think the filters are very cool! Mainly for the readability. Okay, so here are my extension methods on the datacontext:
internal static class SchoolMap
{
internal static School GetSchoolById(this LearningDataContext dataContext, int schoolId)
{
var s = dataContext.Schools.SingleOrDefault(x => x.SchoolId == schoolId);
return new School()
{
ContactNumber = s.ContactNumber,
County = s.LookupCounty.FullName,
FullName = s.FullName,
ShortName = s.ShortName
};
}
internal static IQueryable<School> GetAllSchools(this LearningDataContext dataContext)
{
var schools = from s in dataContext.Schools
orderby s.FullName
select new School()
{
ContactNumber = s.ContactNumber,
County = s.LookupCounty.FullName,
FullName = s.FullName,
ShortName = s.ShortName
};