EntityFramework 6 - 获取DbSet<>没有在上下文中注册模型

时间:2017-02-05 10:08:55

标签: c# entity-framework

在Linq-to-sql中,我能够在没有在上下文中注册模型的情况下获得表。 但是,在EF中我得到The entity type A is not part of the model for the current context.错误。

以下是代码清单:

class Program
  {
    static void Main(string[] args)
    {
      const string constr = @"Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=Test";

      var ctx = new MyContext(constr);
      var table = ctx.GetTable<A>();

      var a = table.FirstOrDefault();

      var efCtx = new EfContext(constr);
      var set = efCtx.Set<A>();
      var b = set.FirstOrDefault();
    }
  }

  [System.Data.Linq.Mapping.Table]
  class A
  {
    [System.Data.Linq.Mapping.Column]
    [Key]
    public Guid Id { get; set; }
    [System.Data.Linq.Mapping.Column]
    public string B { get; set; }
  }

  class EfContext : DbContext
  {
    public EfContext(string con)
      : base(con)
    {
    }
  }

  class MyContext : DataContext
  {
    public MyContext(string fileOrServerOrConnection)
      : base(fileOrServerOrConnection)
    {
    }
  }

此行var set = efCtx.Set<A>();

上会抛出异常

是否可以像使用linq-to-sql一样使用EF?

0 个答案:

没有答案