实体框架 - 选择特定列

时间:2014-03-13 01:52:49

标签: c# web-services entity-framework

这是我的用户模型或类

 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;
        }

我的方法很长,因为我想避免循环引用,但我认为我的步骤不好,需要很多步骤我想知道我有什么为什么我可以用一个查询让用户内部的公司,它也应该返回一个对象类型用户,因为?我真的很抱歉我的英语不好

2 个答案:

答案 0 :(得分:1)

您需要的只是该方法的第一行和最后一行。其余的完全是多余的。通过指定您已经获得公司的包含路径,因此无需单独获取。通过不指定任何其他包含路径,您已经没有获得任何更多相关记录,因此将所有这些属性设置为null是没有意义的。

答案 1 :(得分:0)

你想要做太多的方式。我很确定你的代码实际上不会做你想要的。这就是你所需要的。 (我假设db是一个已经在你的类中实例化过的属性或字段。)

public User getUser(int id)
{
    return db.Users.Find(id);
}

一旦您退回用户,您就可以获得这样的公司

var user = getUser(25);
var userCompany = user.Company;
相关问题