2

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); }

and for bar

internal void Add(Bar _bar){ dbContext.Bar.AddObject(_bar); }

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.

J.W.
  • 17,991
  • 7
  • 43
  • 76
John x
  • 4,031
  • 8
  • 42
  • 67

1 Answers1

4

This should work for you.

internal void Add<T>(T entity) { dbcontext.Set<T>.Add(entity); }

Then you call it like so:

obj.Add(foo);

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.

Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291