我是实体框架的新手。我试图找到将我的选择值返回到我的实体属性的最佳代码 这是我的代码:
private void CustomerForm_Load(object sender, EventArgs e)
{
if (CustomerID != null && CustomerMode !=(int)CustomerModeOperaton.insert)
{
using (var Context = new FactorEntities())
{
var Customercods = from _customers in Context.tblCustomers.Where(c => c.CustomerID == CustomerID) select _customers.CustomerCode;
_tblCustomer.CustomerCode = Customercods.First();
var Customernames = from _customers in Context.tblCustomers.Where(c => c.CustomerID == CustomerID) select _customers.CustomerName;
_tblCustomer.CustomerName = Customernames.First();
var Customerlastname = from _customers in Context.tblCustomers.Where(c => c.CustomerID == CustomerID) select _customers.CustomerLastName;
_tblCustomer.CustomerLastName = Customerlastname.First();
var customerID = from _customers in Context.tblCustomers.Where(c => c.CustomerID == CustomerID) select _customers.CustomerID;
_tblCustomer.CustomerID = customerID.First();
var customerAddresses = from _customers in Context.tblCustomers.Where(c => c.CustomerID == CustomerID) select _customers.CustomerAdresse;
_tblCustomer.CustomerAdresse = customerAddresses.First();
var customerMobile = from _customers in Context.tblCustomers.Where(c => c.CustomerID == CustomerID) select _customers.CustomerCellPhone;
_tblCustomer.CustomerCellPhone = customerMobile.First();
var customerphone = from _customers in Context.tblCustomers.Where(c => c.CustomerID == CustomerID) select _customers.CustomerPhone;
_tblCustomer.CustomerPhone = customerphone.First();
}
}
LoadDataToControl();
}
但是我想知道我是否使用这个代码,我必须使用几个不好的选择,如果我的选择值为null,我该怎么办? 例如这段代码:
_tblCustomer.CustomerPhone = customerphone.First();
答案 0 :(得分:0)
您只需要查询一次客户,并让其在一个对象中返回所有客户的信息。然后,您可以仅为_tblCustomer
字段的作业引用该对象的属性。
如果您使用FirstOrDefault
,那么您可以在尝试使用之前检查返回的对象是否为null
(如果没有与CustomerID
匹配的客户一个你的搜索):
var customer = Context.tblCustomers.FirstOrDefault(c => c.CustomerID == CustomerID);
if (customer != null)
{
_tblCustomer.CustomerCode = customer.CustomerCode;
_tblCustomer.CustomerName = customer.CustomerName;
_tblCustomer.CustomerLastName = customer.CustomerLastName;
_tblCustomer.CustomerID = customer.CustomerID;
_tblCustomer.CustomerAdresse = customer.CustomerAdresse;
_tblCustomer.CustomerCellPhone = customer.CustomerCellPhone;
_tblCustomer.CustomerPhone = customer.CustomerPhone;
}