Get an entity set by its type

c# entity-framework-core

Question

I have a code which works in .Net 4.6 with EF6 but won't work with ef.core. Compiler reports

No overload for method 'Set' takes 1 arguments (CS1501)

  Type type = Type.GetType("ContextName.SomeModel");
  if (type == null) return null;

   var entity = db.Set(type).Find(id);

Basically, I am getting an object by a string name. How to achieve this in .core (v 2.0)?

My imports:

using System;
using System.Collections;
using System.Collections.Generic;

using System.Linq;
using System.Reflection;

using System.Linq.Dynamic.Core;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Shared.Web.MvcExtensions;
1
6
11/20/2017 7:38:40 PM

Accepted Answer

EF Core expose only a generic method Set<T>(). There is no overload that takes the type as parameter like we will do by using Set(Type type) in EF 6.

It seems like you need to find a data from an entity set. EF Core just make it simple because it exposes some instance methods like Find directly into the DbContext class.

So the below code in EF 6

var entity = db.Set(type).Find(id);

Can be rewritten like below in EF Core like this:

var entity = db.Find(type, id);
9
11/20/2017 7:24:20 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow