【发布时间】:2018-01-02 21:48:01
【问题描述】:
我在 Sql-Server 中有五个表,它们使用外键链接。
下面我正在显示数据库表和链接的图像。
例如,我尝试从用户表中获取特定用户 ID 的用户数据,我正在获取所有五个表的内连接行。
但我只需要来自用户表的数据。我尝试编写查询、sql 过程以及 Linq。
总之,我得到了与所有五个表连接的数据。
我怎样才能从一张表中获取数据?
我尝试使用过程,
object[] xparams = {
new SqlParameter("@UserName", "Admin"),
new SqlParameter("@UserPwd", "1234"),
new SqlParameter("@AppType", 1)
};
var user = db.Database.ExecuteSqlCommand("exec proc_authenticate_tocken @UserName, @UserPwd, @AppType ", xparams);
另一个使用查询,
db.Users.SqlQuery("select * from users where PhoneNumber ='"+ user_name + "' and Password = '" + password + "' and TypeId=" + user_type + " and Status = 1;").ToList();
Lsing Linq,
var ty = db.Users.Where(emp => emp.Password == password &&
emp.PhoneNumber == phone_number)
;
下面的代码是实体模型类,使用实体框架自动生成。
public partial class User
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public User()
{
this.TockenPools = new HashSet<TockenPool>();
this.TockenProcesses = new HashSet<TockenProcess>();
}
public int Id { get; set; }
public Nullable<int> TypeId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string PhoneNumber { get; set; }
public string ActualName { get; set; }
public Nullable<System.DateTime> LastLogin { get; set; }
public Nullable<int> LoginCount { get; set; }
public Nullable<int> Status { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<TockenPool> TockenPools { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<TockenProcess> TockenProcesses { get; set; }
public virtual User Users1 { get; set; }
public virtual User User1 { get; set; }
public virtual UserType UserType { get; set; }
}
【问题讨论】:
-
只禁用延迟加载。
-
不需要其他表的相关数据吗?
-
我需要来自其他表的数据,但在这种情况下,我只需要来自 USER 表的数据,稍后我还需要来自其他表的连接数据。
-
检查我的答案。我是根据我对你的Q的理解写的。如果有什么不同,请通知我。
-
我正在尝试禁用lazyLoading,但我仍然遇到同样的错误。
标签: asp.net-mvc entity-framework linq asp.net-web-api