【发布时间】:2019-06-24 12:40:07
【问题描述】:
虽然我对 C# 有很好的理解,但我对 Entity Framework 还是很陌生,但过去 3 年我一直是 PHP 的 Web 开发人员。
我正在尝试将我的 Users 表与我的 Department 表相关联。每次我运行时,它只会在我的 User 类
的 Department 属性上返回 null这是我的建造者
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Users>(entity =>
{
entity.HasOne(user => user.Department);
});
}
部门类
[Table("department", Schema = "settings")]
public class Department
{
[Key]
public long id { get; set; }
public string department_name { get; set; }
public string department_code { get; set; }
}
用户类
[Table("users", Schema = "settings")]
public class Users
{
[Key]
public long id { get; set; }
public string emp_id { get; set; }
public string username { get; set; }
public string password { get; set; }
public string salt { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string middle_initial { get; set; }
public string display_name { get; set; }
public string email { get; set; }
public long proj_id { get; set; }
[ForeignKey("Department")]
public long dept_id { get; set; }
public long job_id { get; set; }
public byte is_active { get; set; }
public DateTime? date_approved { get; set; }
public DateTime? date_created { get; set; }
public DateTime? birthday { get; set; }
public virtual Department Department { get; set; }
}
样本输出
{
"id": 11,
"emp_id": "100156",
"username": null,
"password": "dvser32Z2CaapKM=",
"salt": "o6k234RGOfasf=",
"first_name": "test",
"last_name": "sample",
"middle_initial": "M",
"display_name": "test test",
"email": null,
"proj_id": 7,
"dept_id": 1,
"job_id": 146,
"is_active": 1,
"date_approved": "2018-06-10T13:20:04.513",
"date_created": "2018-06-07T08:20:34.663",
"birthday": null,
"department": null
}
任何帮助我都非常感谢,即使不是针对特定代码,而是针对其背后的概念本身。虽然最好在我理解这个概念时拥有它。
另外,我对关系的理解是否正确,我有一对一的关系?
提前致谢!
【问题讨论】:
标签: entity-framework asp.net-core asp.net-core-2.0