将记录插入DB的通用方法 [英] Generic method to insert record into DB
问题描述
我正在使用实体框架作为ORM,我希望有一个通用的方法来插入不同的实体。例如我有两个实体 foo
和 bar
,我目前正在添加它们,如
I am using Entity Frame work as an ORM and i want to have a single generic method for inserting different entities. say for example i have two entities foo
and bar
and i am currently adding them like
internal void Add(Foo _foo){ dbContext.Foo.AddObject(_foo); }
和栏
internal void Add(Bar _bar){ dbContext.Bar.AddObject(_bar); }
我发现很难把我的头围绕仿制药。请帮助我写一个通用的方法来插入typeOf实体。另外如果有人指导我进入初级教程,我会很棒。
i am finding it difficult to wrap my head around the generics. Please help me in writing a generic method for inserting typeOf entities. Plus if somebody guide me to a beginner level tutorial i'll greatful.
推荐答案
这应该适合你。
This should work for you.
internal void Add<T>(T entity) { dbcontext.Set<T>.Add(entity); }
然后你就这么称呼:
obj.Add(foo);
推断类型,因此您不必直接指定。 Set是一种使用泛型来基于类型检索DbSet的方法,而不必指定集名称。
The type is inferred, so you don't have to specify it directly. Set is a method that uses generics to retrieve the DbSet based on type, rather than having to specify the set name.
这篇关于将记录插入DB的通用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!