繁体   English   中英

在dbcontext中传递通用类名

[英]Passing generic class name in dbcontext

我的实体上下文文件代码:

public partial class MyDbContext : DbContext
{
    //dbset 1
    public DbSet<Customer> Customers { get; set; }

    //dbset 2
    public DbSet<Order> Orders { get; set; }
}

类货运具有方法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);

两者都应使用相同的代码(尝试使其通用,我不确定如何将其强制转换为通用)。 任何帮助都会很棒。 谢谢。

我看不到仅仅为了获取其类型而传递object参数的意义。 您可以为此使用泛型:

public string GetName<T>(DbSet objectContext) where T : BaseEntity {
    IQueryable<T> myCustomer = from p in objectContext
                               select p where p.Id = 1;
    //Get the name
    //Return the name
}

请注意,我为TBaseEntity扩展添加了一个约束。

然后,您所有的实体都应从该抽象类扩展(该抽象类应包含属性IdName以获取名称)。

这样,您不仅可以检索Customer实体的名称,还可以检索Order实体的名称:

string customerName = GetName<Customer>(context);
string orderName = GetName<Order>(context);

如果只有您的Customer实体具有Name属性,那么根本不要使用泛型,那么最好显式定义类型:

public string GetName(context) {
    IQueryable<Customer> customer = from p in context
                                    select p where p.Id = 1;
    //Get the name
    //Return the name
}

像很多人一样,包括我本人在内,您并没有看到数据类型和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属性的特定基类或接口。 对于自动生成的EF类,唯一的选择是接口。

您的代码还存在其他问题,但这涵盖了您实际要问的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM