[英]Entity framework - select specific columns
這是我的用戶模型或類
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; }
這是我的[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;
}
我的方法很長一段時間,因為我想避免循環引用,但是我認為我的步驟不好,它需要很多步驟,我想知道我為什么可以通過一個查詢將公司納入用戶內部,並且還應該返回一個對象輸入用戶是因為? 我真的很抱歉我的英語不好
您所需要做的就是該方法的第一行和最后一行。 其余的完全多余。 通過指定“包含”路徑,您已經可以擁有公司,因此無需單獨獲取。 通過不指定任何其他包含路徑,您就不會再獲得任何相關記錄,因此將所有這些屬性設置為null是沒有意義的。
你試圖做太多 。 我很確定您的代碼實際上不會執行您想要的操作。 這就是您所需要的。 (我假設db
是已經在您的類中實例化的屬性或字段。)
public User getUser(int id)
{
return db.Users.Find(id);
}
一旦返回用戶,您就可以像這樣獲得公司
var user = getUser(25);
var userCompany = user.Company;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.