实体框架-选择特定的列
本文关键字:选择 框架 实体 | 更新日期: 2023-09-27 17:50:11
这是我的用户模型或类
public int UserID { get; set; }
public string UserName { get; set; }
public string UserPassword { get; set; }
public int CompanyID { get; set; }
public int BranchID { get; set; }
public bool RecordState { get; set; }
public virtual Branch Branch { get; set; }
public virtual Company Company { get; set; }
这是我公司的类
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public string CompanyShortName { get; set; }
public string CompanyAddress { get; set; }
public string CompanyPhone { get; set; }
public string CompanyEmail { get; set; }
public string CompanyFax { get; set; }
public bool RecordState { get; set; }
public virtual List<Branch> Branches { get; set; }
public virtual List<Customer> Customers { get; set; }
public virtual List<Market> Markets { get; set; }
public virtual List<Seller> Sellers { get; set; }
public virtual List<User> Users { get; set; }
this my [WebMethod]
public User getUser(int id)
{
User user = db.Users
.Include(c => c.Company)
.Where(i => i.UserID == id)
.FirstOrDefault<User>();
Company company = db.Companies
.Where(i => i.CompanyID == user.CompanyID )
.FirstOrDefault<Company>();
company.Branches = null;
company.Customers = null;
company.Markets = null;
company.Sellers = null;
company.Branches = null;
company.Users = null;
user.Company = company;
return user;
}
我的方法很长,因为我想避免循环引用,但我认为我的步骤是不好的,它需要很多步骤,我想知道我有任何为什么我可以得到公司内部用户与一个查询,它也应该返回一个对象类型的用户,因为?很抱歉我的英语很差
您所需要的只是该方法的第一行和最后一行。其余的都是多余的。通过指定Include路径,您已经获得了公司,因此不需要单独获得它。通过不指定任何其他包含路径,您已经没有获得任何更多相关记录,因此将所有这些属性设置为null是没有意义的。
你做得太多了。我很确定你的代码不会做你想做的事。这就是你所需要的。(我假设db
是一个已经在你的类中实例化的属性或字段。)
public User getUser(int id)
{
return db.Users.Find(id);
}
一旦你返回User,你可以得到这样的公司
var user = getUser(25);
var userCompany = user.Company;