Saturday, May 09, 2009

LINQ to SQL Mapping…Saving

Okay, so I made a new Save method on my repository like so:

public interface ISchoolRepository
{
void Save(School school); //School of my model not the db school object
School GetSchoolById(int schoolId);
IQueryable<School> GetAll();
IQueryable<Student> GetEnrolledStudentsBy(int schoolId);
}

So then I implemented the new Save method like this:

public void Save(Core.Model.School school)
{
using (var db = new LearningDataContext())
{
var currentSchool = SchoolMap.GetDbSchoolFrom(school);
var originalSchool = dc.Schools.SingleOrDefault(x => x.SchoolId == school.Id);
     if (originalSchool == null)
db.Schools.InsertOnSubmit(currentSchool);
else
db.Schools.Attach(currentSchool, originalSchool);

db.SubmitChanges();
}
}

You should notice two things about the above method. One is that I have a static method called GetDbSchoolFrom(Core.Model.School school), which maps my model school to the db school. The other being that I’m using two datacontexts. One of them is defined on the class, dc, like in this post and the other is local to the method, db. So I still have my db/linq to sql objects as internal, which was one of my main goals and I feel pretty comfortable with this setup and maintainability.

Here is the GetDbSchoolFrom method:
internal static DataAccess.Impl.School GetDbSchoolFrom(School school)
{
var s = new DataAccess.Impl.School();
s.ContactNumber = school.ContactNumber;
s.FullName = school.FullName;
s.SchoolId = school.Id;
s.ShortName = school.ShortName;
s.CountyId = school.County.Id;
return s;
}
On another project, I went ahead and made a lot of DB changes so I could really test my model dependency on the db schema. I was happy to say that I only had to touch my mapper classes. Everything else remained the same.

As always, please make any comments you feel necessary and definitely let me know if you find any holes or issues with my code. Thanks!

Thank you Jimmy Bogard for telling me about the Windows Live Writer from Visual Studio plugin.


kick it on DotNetKicks.com

blog comments powered by Disqus
Related Posts Plugin for WordPress, Blogger...