Update SqlCE database Linq-to-Sql
When I update the database, I have to hard code mapping of each property, because using attach results in exception. This does not seem too elegant. Is there some easier solution here I'm not aware of? My code is below, showing the "MapData" method I call for this purpose:
Btw, entity classes (here; Users) are autogenerated with SqlMetal.
Public Class UserDataService
Public Sub Save(ByVal user As Users)
Dim ctx As New TestDB(connection)
Dim id As Integer 开发者_开发技巧= user.Id
If user.Id = 0 Then
Insert(user)
Else
Dim q = (From n In ctx.Users Where n.Id = id Select n).Single
q.MapData(user)
For Each o In user.Orders
o.Save()
Next
' ctx.Users.Attach(user, q) ' Does not work
' ctx.Users.Attach(user, True) ' Does not work
End If
ctx.SubmitChanges()
ctx.Dispose()
End Sub
End Class
Partial Public Class Users
Public Sub MapData(ByVal row As Users)
Me.Name = row.Name
End Sub
End Class
EDIT1:
Exceptions:
ctx.Users.Attach(user, q)
Cannot add an entity with a key that is already in use.
ctx.Users.Attach(user, True)
An entity can only be attached as modified without original state if it declares a version member or does not have an update check policy.
EDIT2:
I tried to add a column timestamp, which I believe is supposed to satisfy the last mentioned exception. So I add the column shown here. This doesn't help, but perhaps I need to make some further settings for that to be effective?
This way should work:
ctx.Users.Attach(user)
ctx.Refresh(RefreshMode.KeepCurrentValues, user) 'this line is important
ctx.SubmitChanges()
This is my console test app(it works), in C# though:
class Program
{
public static void Main(string[] args)
{
var t = new Test();
Customer c = t.GetCustomer();
c.CompanyName = "X";
t.AttachCustomer(c);
}
class Test
{
public Customer GetCustomer()
{
Customer cust;
using(DataContext db = new DataContext())
{
cust = db.Customers.Where(x => x.CustomerID == "ALFKI").Single();
db.Dispose();
}
return cust;
}
public void AttachCustomer(Customer cx)
{
using (DataContext db = new DataContext())
{
db.Customers.Attach(cx);
db.Refresh(RefreshMode.KeepCurrentValues, cx);
db.SubmitChanges();
db.Dispose();
}
}
}
}
精彩评论