从类返回的值将恢复为 null
本文关键字:恢复 null 返回 | 更新日期: 2023-09-27 18:22:08
我创建了一个新的承包商对象"gc",它调用方法GetConcontracter((来返回所有属性。它返回的结果是正确的,但是"gc"对象显示所有"NULL"。我假设我在 aspx.cs 页面中做错了什么?
aspx.cs
protected void fvWasteCollected_ItemCommand(object sender, FormViewCommandEventArgs e)
{
if (e.CommandName.Equals("Insert")){
ValidationSummaryWasteDetail.ValidationGroup = "WasteReceivedDetail";
if (IsValid) {
odsMRWWasteCollectedDetail.InsertParameters["WasteTypeId"].DefaultValue = ddlWasteCollectedType.SelectedValue;
odsMRWWasteCollectedDetail.InsertParameters["DisposalMethodId"].DefaultValue = ddl_disposalMethod.SelectedValue;
Contractor gc = new Contractor();
gc.GetContractor(2);
var contractorName = gc.MRWContractorName;
}
}
}
。.cs
public class Contractor
{
public Contractor GetContractor(int MRWContractorId)
{
using (DataAccessLINQDataContext db = new DataAccessLINQDataContext())
{
var result = db.MRWContractors.Where(c => c.MRWContractorId == MRWContractorId).Select(c => new Contractor
{
MRWContractorId = c.MRWContractorId,
MRWContractorName = c.MRWContractorName,
MRWContractorAddress = c.MRWContractorAddress,
MRWContractorCity = c.MRWContractorCity,
MRWContractorStateCode = c.MRWContractorStateCode,
MRWContractorZipCode = c.MRWContractorZipCode,
MRWContractorPhone = c.MRWContractorPhone,
MRWContractorFax = c.MRWContractorFax,
MRWContractorEmail = c.MRWContractorEmail
}).SingleOrDefault();
return result;
}
}
public int MRWContractorId { get; set; }
public string MRWContractorName { get; set; }
public string MRWContractorAddress { get; set; }
public string MRWContractorCity { get; set; }
public string MRWContractorStateCode { get; set; }
public int? MRWContractorZipCode { get; set; }
public string MRWContractorPhone { get; set; }
public string MRWContractorFax { get; set; }
public string MRWContractorEmail { get; set; }
}
当你不把它分配给某物时,你会失去gc
的值。
试试这个:
var contractor = gc.GetContractor(2);
var contractorName = contractor.MRWContractorName;
您正在创建仅用于调用 GetContractor
方法的对象的一个空实例。GetContractor
方法创建另一个包含数据的实例,该实例被返回,但您只需丢弃该实例,并期望数据在从未填充的第一个实例中可用。
将 GetContractor
方法设为静态,以便不需要实例来调用它:
public static Contractor GetContractor(int MRWContractorId)
现在,您可以调用该方法来获取包含数据的实例,而无需先创建空实例:
Contractor gc = Contractor.GetContractor(2);
string contractorName = gc.MRWContractorName;