获取按类型设置的实体

Sim*_*ich 4 c# entity-framework-core

我有一个可以在.Net 4.6中使用EF6的代码,但是不能在ef.core中使用。编译器报告

方法'Set'的重载不接受1个参数(CS1501)

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

   var entity = db.Set(type).Find(id);
Run Code Online (Sandbox Code Playgroud)

基本上,我是通过字符串名称获取对象的。如何在.core(v 2.0)中实现呢?

我的进口:

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;
Run Code Online (Sandbox Code Playgroud)

Cod*_*und 8

EF Core仅公开一种通用方法Set<T>()。没有像我们Set(Type type)在EF 6中那样使用类型作为参数的重载。

似乎您需要从实体集中查找数据。EF Core只是使其简单,因为它将某些实例方法(例如Find直接向DbContext类公开)。

因此,EF 6中的以下代码

var entity = db.Set(type).Find(id);
Run Code Online (Sandbox Code Playgroud)

可以像下面这样在EF Core中进行重写:

var entity = db.Find(type, id);
Run Code Online (Sandbox Code Playgroud)

  • 我不认为 EFC 从 `DbContext` 中公开这样的方法来“让它变得简单”——没有其他选择,因为 EFC 根本没有非通用的 `DbSet` 类 (3认同)
  • 这对于“查找”以外的其他功能也适用。我需要“添加(实体)”方法。 (2认同)