从另一个类实例返回IQueryable <t>

时间:2016-01-08 00:20:04

标签: c# .net entity-framework linq iqueryable

我想要完成的是创建一个返回通用public class FileUploadController { private static final String SERVER_UPLOAD_LOCATION_FOLDER = System .getProperty("catalina.home") + "/kukus/images/"; private static final Logger logger = LoggerFactory .getLogger(FileUploadController.class); /** * Upload single file using Spring Controller */ @RequestMapping(value = "/uploadFile", method = RequestMethod.POST) public @ResponseBody String uploadFileHandler(@RequestParam("file") MultipartFile file) { System.out.println("File"+file); if (!file.isEmpty()) { try { byte[] bytes = file.getBytes(); // Creating the directory to store file System.out.println("Catalina base" +System.getProperty("catalina.base")); String rootPath = SERVER_UPLOAD_LOCATION_FOLDER; System.out.println("rootPath" +rootPath); File dir = new File(rootPath + File.separator + "tmpFiles"); System.out.println("File Dir" +dir); if (!dir.exists()) dir.mkdirs(); // Create the file on server File serverFile = new File(dir.getAbsolutePath() + File.separator); System.out.println("AbsolutePath" +dir.getAbsolutePath()+ "ServerFile" +serverFile.getAbsolutePath()); BufferedOutputStream stream = new BufferedOutputStream( new FileOutputStream(serverFile)); stream.write(bytes); stream.close(); logger.info("Server File Location=" + serverFile.getAbsolutePath()); return "You successfully uploaded file="; } catch (Exception e) { return "You failed to upload " + " => " + e.getMessage(); } } else { return "You failed to upload " + " because the file was empty."; } } 的基类,并使用来自另一个类实例的IQueryable<T>进一步过滤。 ES。 基类返回所有记录,调用类从那里开始过滤。

这是基类,getDealer_query是返回主IQueryable

的方法
IQueryable

这是另一个类 public class Dealer { public DAL.DBConn_Nav db = null; public G4.Elements.Identity oIdentity = null; public Dealer() { oIdentity = new G4.Elements.Identity(); oIdentity.read(); } public IQueryable<outerViewModel.NavisionDAL.vmDealer> getDealer_query() { IQueryable<vmDealer> dealer = (from d in db.DENTALICA_S_P_A__Customer select new vmDealer() { idDealer = d.No_, name = d.Name + (d.Name_2.Length > 0 ? " " + d.Name_2 : ""), address = d.Address + (d.Address_2.Length > 0 ? " " + d.Address_2 : ""), city = d.City, zip = d.Post_Code, county = d.County, email = d.E_Mail, phone = d.Phone_No_, fax = d.Fax_No_, vat = d.VAT_Registration_No_, ssn = d.Fiscal_Code, businessAreaCode = d.Business_Area_Code, businessZoneCode = d.Business_Zone_Code, clienteDiretto = (d.Cliente_Diretto == (byte)1 ? true : false), aggancioOrdiniWeb = (d.Deposito_Agg__Ordini_Web == (byte)1 ? true : false), aggancioOrdiniG4 = (d.Deposito_Agg__Ordini_G4 == (byte)1 ? true : false), notUse = (d.Not_Use == (byte)1 ? true : false), blocked = d.Blocked, shipmentMethodCode = d.Shipment_Method_Code, paymentTermsCode = d.Payment_Terms_Code, paymentMethodCode = d.Payment_Method_Code, shippingAgentCode = d.Shipping_Agent_Code, customerPriceGroup = d.Customer_Price_Group, customerDiscountGroup = d.Customer_Disc__Group, identificaCliente = d.Identifica_Cliente }); return dealer; } ,它从Customer的实例调用该方法,最后列出数据。

Dealer

但它不起作用!我得到一个通用&#34;对象未设置为实例...&#34;。

即使我尝试调试,我也无处可去,因为光标不会停止。

为了使它工作,我必须从Customer继承Dealer类,但这不是我想要的。

我想我在这里遗漏了一些基本的东西。

任何想法?

编辑 - 简化样本 我添加了相同代码的简化示例。

public class Customer
{
    G4.Elements.Identity oIdentity = null;
    DAL.DBConn_Nav navDB = null;

    public Customer()
    {
        //oIdentity = new G4.Elements.Identity();
        //oIdentity.read();
    }

    ///// <summary>
    ///// Recupera l'elenco dei clienti Navision (i Depositi pr G4) visibili ad un particolare utente
    ///// </summary>
    ///// <returns></returns>
    public IQueryable<outerViewModel.NavisionDAL.vmDealer> getCustomerForOperator_query()
    {
        string idOperator = !string.IsNullOrEmpty(oIdentity.selectedId) ? oIdentity.selectedId : oIdentity.id;

        using (navDB = new DAL.DBConn_Nav()) {
            G4.Models.NavisionDAL.Dealer oD = new G4.Models.NavisionDAL.Dealer();
            // Tutti i Clienti
            IQueryable<outerViewModel.NavisionDAL.vmDealer> allCustomerList_query = oD.getDealer_query();
            IQueryable<outerViewModel.NavisionDAL.vmDealer> customerForOperator_query = (from c in allCustomerList_query                                                                                join cForOp in navDB.DENTALICA_S_P_A__SalesPerson_Customer on c.idDealer equals cForOp.Customer_No_
                                                                                         where cForOp.Salesperson_Code.Equals(idOperator)
                                                                                         && cForOp.Starting_Date < DateTime.Now
                                                                                         && (cForOp.Ending_Date.Equals(new DateTime(1753, 1, 1)) || cForOp.Ending_Date > DateTime.Now)
                                                                                         && c.notUse.Equals(false)
                                                                                      select c).Distinct();

            return customerForOperator_query;
        }
    }

    public List<G4.outerViewModel.NavisionDAL.vmDealer> getCustomerForOperator()
    {
        using (navDB = new DAL.DBConn_Nav())
        {
            G4.Models.NavisionDAL.Dealer oD = new G4.Models.NavisionDAL.Dealer();
            return getCustomerForOperator_query().ToList();
        }
    }

2 个答案:

答案 0 :(得分:2)

您的班级Dealer中没有设置db的实例。

public DAL.DBConn_Nav db = null;

所以即使在Customer中你拨打using (navDB = new DAL.DBConn_Nav()),你也没有将navDB传递给Dealer,所以当你致电getDealer_query()时,你会得到一个空引用异常。

根据您的简化示例,我建议使用以下代码:

public class Dealer1
{
    internal IQueryable<vmDealer> getDealer_query(DAL.DBConn_Nav db)
    {
        return
            from d in db.DENTALICA_S_P_A__Customer
            select new vmDealer()
            {
                idDealer = d.No_,
                name = String.Join(" ", d.Name, d.Name_2)
            };
    }
}

public class Customer1
{
    internal IQueryable<vmDealer> getCustomerForOperator_query(DAL.DBConn_Nav db)
    {
        return new Dealer1().getDealer_query(db).Where(i => i.name.StartsWith("AAA"));
    }

    public List<vmDealer> getCustomerForOperator()
    {
        using (var db = new DAL.DBConn_Nav())
        {
            return getCustomerForOperator_query(db).ToList();
        }
    }
}

这清楚地允许您分离责任,但它可以让您完全控制db实例 - 完成后您需要处理它。

答案 1 :(得分:0)

allCustomerList_query为空的原因不应该是

要确认getDealer_query方法中的linq语句是否有效,我会将您的代码更改为:

        List<outerViewModel.NavisionDAL.vmDealer> something = new List<outerViewModel.NavisionDAL.vmDealer>();
        IQueryable<outerViewModel.NavisionDAL.vmDealer> test = something.AsQueryable();
        return test;

在任何情况下,为了防止对象引用错误,您需要保证返回一个实例,从代码示例中我无法实际告知。

相当奇怪的是,你无法在getDealer_query方法中找到一个断点。您是否在运行多个线程的测试中运行此操作?可能发生的是另一个线程正在引发未处理的异常,因此整个测试停止。尝试在return dealergetDealer_queryG4.Models.NavisionDAL.Dealer oD = new G4.Models.NavisionDAL.Dealer();之前设置断点。假设没有其他线程,代码必须停止其中一个。

最后请注意,查看代码时,我不知道实例化db的位置。如果没有实例化,您将在此行上收到对象引用错误:

    `IQueryable<vmDealer> dealer = (from d in db.DENTALICA_S_P_A__Customer`