Entity Framework 6 Code First - 使用现有数据库的 2 个表之间的关系
Entity Framework 6 Code First - Relationship between 2 tables using an existing DB
我很难从 Detail table 获取数据,但我可以从 DetailKey table 获取数据。这是我到目前为止所做的,感谢您的帮助。
public class DetailKey
{
public int Id { get; set; }
public string System { get; set; }
public string KeyValue { get; set; }
public Nullable<int> DetailId { get; set; }
}
public class Detail
{
public Detail()
{
this.DetailKeys = new HashSet<DetailKey>();
}
public int Id { get; set; }
public System.DateTimeOffset CreatedDatetime { get; set; }
public System.DateTimeOffset UpdatedDatetime { get; set; }
public string Name { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
public virtual ICollection<DetailKey> DetailKeys { get; set; }
}
public class MyDbContext : DbContext
{
public MyDbContext() :base("name=dbConnectionString"){}
public DbSet<Detail> Details {get; set;}
public DbSet<DetailKey> DetailKeys {get; set;}
}
using(var db = new MyDbContext())
{
db.Details; // I get no result.
db.DetailKeys; // I get an exception System.Data.Entity.Core.EntityCommandExecution.Exception
{
如果你的意思是为什么在DetailKey中没有相关的Detail class class;
您应该将 外键 添加到 DetailKey table
我认为 Detail table 的问题在于存在一些不匹配的字段。但是,我通过使用 ADO.NET 实体数据模型然后从数据库中使用 select 代码优先来解决这个问题。现在我得到了我所有的实体和所有数据。真不敢相信我花了这么多时间在这上面。
我很难从 Detail table 获取数据,但我可以从 DetailKey table 获取数据。这是我到目前为止所做的,感谢您的帮助。
public class DetailKey
{
public int Id { get; set; }
public string System { get; set; }
public string KeyValue { get; set; }
public Nullable<int> DetailId { get; set; }
}
public class Detail
{
public Detail()
{
this.DetailKeys = new HashSet<DetailKey>();
}
public int Id { get; set; }
public System.DateTimeOffset CreatedDatetime { get; set; }
public System.DateTimeOffset UpdatedDatetime { get; set; }
public string Name { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
public virtual ICollection<DetailKey> DetailKeys { get; set; }
}
public class MyDbContext : DbContext
{
public MyDbContext() :base("name=dbConnectionString"){}
public DbSet<Detail> Details {get; set;}
public DbSet<DetailKey> DetailKeys {get; set;}
}
using(var db = new MyDbContext())
{
db.Details; // I get no result.
db.DetailKeys; // I get an exception System.Data.Entity.Core.EntityCommandExecution.Exception
{
如果你的意思是为什么在DetailKey中没有相关的Detail class class;
您应该将 外键 添加到 DetailKey table
我认为 Detail table 的问题在于存在一些不匹配的字段。但是,我通过使用 ADO.NET 实体数据模型然后从数据库中使用 select 代码优先来解决这个问题。现在我得到了我所有的实体和所有数据。真不敢相信我花了这么多时间在这上面。