我创建了一个新的Contractor对象" gc"调用方法GetContractor()来返回所有属性。它返回的结果是正确的,但" 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; }
}
答案 0 :(得分:3)
如果不将其分配给某些内容,则会失去gc
的值。
请改为尝试:
var contractor = gc.GetContractor(2);
var contractorName = contractor.MRWContractorName;
答案 1 :(得分:1)
您正在创建一个仅用于调用GetContractor
方法的对象的空实例。 GetContractor
方法创建另一个包含数据的实例,该实例将被返回,但您只需抛弃该实例,并期望数据在第一个从未填充过的实例中可用。
将GetContractor
方法设为静态,这样您就不需要实例来调用它:
public static Contractor GetContractor(int MRWContractorId)
现在,您可以调用该方法来获取包含数据的实例,而无需先创建空实例:
Contractor gc = Contractor.GetContractor(2);
string contractorName = gc.MRWContractorName;