我的实体上下文文件代码:
public partial class MyDbContext : DbContext
{
//dbset 1
public DbSet<Customer> Customers { get; set; }
//dbset 2
public DbSet<Order> Orders { get; set; }
}
类 Shipments 有一个方法 GetCustomerName
public class Shipments
{
public string GetName(object caller, System.Data.Entity.DbSet objectContext)
{
//This one passes.
IQueryable<Customer> myCustomer = from p in objectContext
select p where p.Id=1; //get customer name
//This one fails
IQueryable<caller.GetType()> myCustomer = from p in objectContext
select p where p.Id=1; //get customer name
}
}
问题:我想删除那里的 Customer 类的硬编码,而是通过传递类名作为参数来调用此方法?
我该如何实现这个?在这种情况下,caller.GetType().Name
对我不起作用。
GetName(Order, mydbContext);
GetName(Customer, mydbContext);
两者都应该使用相同的代码(尝试使其通用,我不知道如何将其转换为通用)。任何帮助都会很棒。谢谢。
最佳答案
像很多人一样,包括我自己,您没有看到数据类型和 Type
类的实例之间的区别。数据类型是在编译时已知的东西。当您调用GetType
时,您返回的是一个数据类型为Type
的对象。它包含有关数据类型的信息,但它本身不是数据类型。
您需要做的就是使您的 GetName
方法也通用:
public string GetName<T>(T caller, System.Data.Entity.DbSet objectContext)
{
IQueryable<T> myEntity = from p in objectContext
select p where p.Id=1; //get customer name
}
为了能够做到这一点,编译器必须知道类型 T
实际上具有 Id
属性。这意味着 T
必须被限制为声明 Id
属性的特定基类或接口(interface)。对于自动生成的 EF 类,接口(interface)是唯一的选择。
您的代码还存在其他问题,但这涵盖了您实际询问的内容。
关于c# - 在 dbcontext 中传递通用类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26985090/