Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an entity set by its type

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;
like image 358
Simeon Grigorovich Avatar asked Nov 20 '17 18:11

Simeon Grigorovich


1 Answers

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);
like image 71
CodeNotFound Avatar answered Sep 20 '22 22:09

CodeNotFound