I have a method in a datalibrary that looks like this
public IEnumerable<GeneralContractLine> getContractLines(int GeneralContractID)
{
return db.GeneralContractLines.Where(l => l.FKGeneralContractID == GeneralContractID);
}
public void UpdateContractLine(GeneralContractLine line)
{
//Update the object "line"
}
The first method is ok, the db is just the datacontext object that is been initiliazied earlier.
The update method I would like to do something like:
db.GeneralContractLine.update(line);
db.submitChanges();
I know I can find the object, replace it then update, but 开发者_开发百科are there any better way?
I can predict that you use the db object to get the GeneralContractLine object somewhere in your code and do some changes on it's properties and you want to save these updates so my solution for you is to just use the db.submitChanges() and all changes done on the GeneralContractLine object will be saved.
with Linq to SQL, you just change the object and then call SubmitChanges when you're done.
public void UpdateContractLine(GeneralContractLine line)
{
//Update the object "line"
line.PropertyX = "Foo";
db.SubmitChanges();
}
what you could do is create a extension method for the Table class for GeneralContractLine and add a method into it called Update().
Something Like
public static class LinqToSqlExtensions
{
public static void Update(this System.Data.Linq.Table<GeneralContractLine> table, GeneralContractLine item)
{
var connectedItem = table.FirstOrDefault(x => x.ID == item.ID);
//Update logic in this case updating only the name
connectedItem.Name = item.Name;
table.Context.SubmitChanges();
}
}
just as a not, i have not tested any of this but it may be something that is worth trying
Oh and if it works, calling it should just be a case of adding a using statement to the namespace and then calling db.GeneralContractLine.Update(line);
精彩评论