問題描述
我想通過單一方法將我的 UserCompany
對象插入數據庫.比如將元素傳遞給這個函數,取它并插入右表".
I'd like to insert my UserCompany
object into the database trought a single method. Such as passing the element to this function, take it and "insert in the right table".
通常在實體中(例如 LINQ to XML)我會做類似的事情:
Usually in Entity (such as LINQ to XML) I do somethings like:
db.Company.UsersCompany.Add(UserCompany);
db.SubmitChanges();
但這里的問題是我需要在使用 .Add()
之前指定表 UsersCompany
和 Company
.我想(因為我想為每種類型的對象/表的插入執行一個函數)擺脫這個.比如有一個:
but the problem here is that I need to specify the table UsersCompany
and Company
before using the .Add()
.
I'd like (since I want to do ONE function for the insert for each type of object/table) get rid of this. Such as having a:
UserCompany.InsertMySelf();
或
db.SmartAdd(UserCompany);
它知道如何自動插入表格,在哪里以及如何插入.
and it know how to insert the table, where and how, automatically.
可以這樣做嗎?有什么策略嗎?
Is it possible to do this? Is there any strategies?
推薦答案
你可以用泛型解決這個問題:
You can solve this with generics:
Public Sub AddEntities(Of TEntity)(entities As IEnumerable(Of TEntity))
For Each ent In entities
_db.Set(Of TEntity).Add(ent)
Next
_db.SaveChanges()
End Sub
很抱歉使用 VB...在 C# 中:
Sorry for using VB... In C#:
public void AddEntities<TEntity>(IEnumerable<TEntity> entities)
{
foreach(ent in entities)
{
_db.Set<TEntity>.Add(ent);
}
_db.SaveChanges();
}
這篇關于自動/智能插入“本身"目的的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!