DbSet.Cast<TEntity>() Error: Cannot create a DbSet<IEntity> from a non-generic DbSet for objects of type 'Entity'

醉酒当歌 提交于 2019-11-30 14:09:56

For this, I would actually suggest using reflection. In the constructor of your DbContext, you can set a property to the function pointer:

method = this.GetType().GetMethod("Set", new Type[0]).MakeGenericMethod(typeof(UserImplementation));

You can then invoke this using:

method.Invoke(this, new object[0]);

And this should return an object of type DbSet<UserImplementation> which the .Cast<>() method can then be invoked on.

replace

nonGeneric.Cast<IUser>();

by

Enumerable.Cast<IUser>(nonGeneric);

Ok i know nothing about Entity framework but from looking at the docs

http://msdn.microsoft.com/en-us/library/gg696521%28v=vs.103%29.aspx

DbSet<TEntity> item = DbContext.Set<TEntity>;

so actually your code would be the same as this:

DbSet<User> nonGeneric = context.Set<User>();

and to get a IUser

DbSet<IUser> nonGeneric = context.Set<User>();

or maybe

var generic = nonGeneric.Cast<DbSet<IUser>>();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!