LINQ 2 SQL: Partial Classes
I need to set the ConnectionString for my DataContext's based on an AppSetting. I am trying to do this by creating a Partial Class for each DataContext. The below is what I have so far and I am wondering if I am overlooking something?
Specifically, am I dealing with my DataContext's correctly(disposing, staleness, etc)?
Doing it this way will I have issues with Updates and Inserts? Is the file BLLAspnetdb.cs
useful or neccessary in the least or should all of that be in the generated partial class AspnetdbDataContext
file?
In short, is this an acceptable structure or will this cause me issues as I elaborate it?
dbml File Name = Aspnetdb.dbml
Partial Class File Name = Aspnetdb.cs
partial class AspnetdbDataContext
{
public static bool IsDisconnectedUser
{
get
{
return Convert.ToBoolean(ConfigurationManager.AppSettings["IsDisconnectedUser"]) == true;
}
}
public static AspnetdbDataContext New
{
get
{
var cs = IsDisconnectedUser ? Settings.Default.Central_aspnetdbConnectionString : Settings.Default.aspnetdbConnectionString;
return new AspnetdbDataContext(cs);
}
}
}
My Created File Name = BLL开发者_运维百科Aspnetdb.cs
public class BLLAspnetdb
{
public static IList WorkerList(Guid userID)
{
var DB = AspnetdbDataContext.New;
var workers = from user in DB.tblDemographics
where user.UserID == userID
select new { user.FirstName, user.LastName, user.Phone };
IList theWorkers = workers.ToList();
return theWorkers;
}
public static String NurseName(Guid? userID)
{
var DB = AspnetdbDataContext.New;
var nurseName = from demographic in DB.tblDemographics
where demographic.UserID == userID
select demographic.FirstName +" " + demographic.LastName;
return nurseName.SingleOrDefault();
}
public static String SocialWorkerName(Guid? userID)
{
var DB = AspnetdbDataContext.New;
var swName = from demographic in DB.tblDemographics
where demographic.UserID == userID
select demographic.FirstName + " " + demographic.LastName;
return swName.SingleOrDefault();
}
}
see this previous question and the accepted answer for background on how I got to here... switch-connectionstrings-between-local-and-remote-with-linq-to-sql
You should dispose of your context, since it is disposable. Consider wrapping the statements in a using block whenever you create a new context.
I propably would express the static "New" property as a "Create" method instead. It is not normal for properties to be creating new objects, so other developers that need to use the code might be surprised by the behavior.
Other than that, your approach will work. When you acquire your context, the logic to determine the connection string runs, and you will get a context constructed with the correct connection string.
I would not all of your methods and properties be static if I were you. It defies good OO design, and makes you very locked in to a specific implementation - however, I guess that is not in scope for the question.
精彩评论