К вашему сведению, мне удалось написать простой класс для выполнения общей операции CUD для LINQ to SQL.
'Class GenericCUD.vb
Импорт System.Linq.Expressions
Импортирует System.Data.Linq
Открытый класс GenericCUD
Public Shared Sub Insert(Of T As Class)(ByVal theEntity As T)
Using db As New DemoDataContext()
db.GetTable(Of T)().InsertOnSubmit(theEntity)
db.SubmitChanges()
End Using
End Sub
Public Shared Sub Update(Of T As Class)(ByVal originalEntity As T, ByVal newEntity As T)
Using db As New DemoDataContext()
db.GetTable(Of T)().Attach(newEntity, originalEntity)
db.Refresh(RefreshMode.KeepCurrentValues, newEntity)
db.SubmitChanges()
End Using
End Sub
Public Shared Sub Delete(Of T As Class)(ByVal theEntity As T)
Using db As New DemoDataContext()
db.GetTable(Of T)().Attach(theEntity)
db.GetTable(Of T).DeleteOnSubmit(theEntity)
db.Refresh(RefreshMode.KeepCurrentValues, theEntity)
db.SubmitChanges()
End Using
End Sub
Конечный класс
Как пользоваться классом:
'Using Insert
Dim ta As New TestAuthor
ta.FirstName = TextBox1.Text
ta.LastName = TextBox2.Text
GenericCUD.Insert(ta)
'Using Update
Dim original As New TestAuthor
original.Id = 3
Dim newEntity As New TestAuthor
newEntity.Id = original.Id
newEntity.FirstName = TextBox1.Text
newEntity.LastName = TextBox2.Text
GenericCUD.Update(original, newEntity)
'Using Delete
Dim ta As New TestAuthor
ta.Id = 7
GenericCUD.Delete(ta)
Я прочитал много постов во многих блогах. Вот некоторые из них, которые действительно помогли мне заставить работать GenericCUD:
- LINQ, Lambda и Generics: вставить и удалить
- LINQ to SQL CRUD
- Как заставить LINQ to SQL проверять наличие изменений после присоединения
Итак, что вы думаете о классе GernericCUD выше? Пожалуйста, дайте мне комментарий, потому что я хочу улучшить его. Спасибо.