实体框架6代码优先 - 使用现有数据库的2个表之间的关系

时间:2016-06-18 06:06:01

标签: c# entity-framework code-first

我很难从Detail表中获取数据,但我可以从DetailKey表中获取数据。这是我到目前为止所做的,感谢您的帮助。

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
{

2 个答案:

答案 0 :(得分:0)

如果您的意思是为什么 DetailKey 类中没有相关的详细信息类;

您应该将外键添加到 DetailKey

答案 1 :(得分:0)

我认为Detail表的问题在于有一些不匹配的字段。但是,我通过使用ADO.NET实体数据模型然后从数据库中选择Code First来解决此问题。现在我得到了所有实体和所有数据。我简直不敢相信我花了这么多时间。