实体框架 - 继承自模型

时间:2017-04-08 17:22:13

标签: c# entity-framework

我是实体框架的新手,我已经按照在线教程创建了我的SQL Server数据库,并创建了几个模型和一个上下文类来包含访问它们的属性。

这是我的帐户模型:

public class Account
{
    public int ID { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
}

这是我的上下文类:

 public class DashContext : DbContext
{
    public DashContext()
    : base(Constants.ConnectionString)
    {
        this.Configuration.LazyLoadingEnabled = true;
        this.Configuration.ProxyCreationEnabled = false;
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Database.SetInitializer<DashContext>(null);
    }

    public DbSet<Account> Accounts { get; set; }
}

这样做 - 当我访问DbSet属性时,我可以访问我的数据库中的所有帐户。

但是,我想创建一个包含更多属性的Account类的实现,因为它必须与我的程序交互。

所以,我尝试做以下事情:

public class GameAccount : Account
{
    public int SomeSpecialProperty { get; set; }
}

但是,当我使用我的上下文类来获取Account对象时,我不确定如何将其转换为GameAccount。我知道我可以创建一个构造函数,将属性从Account复制到GameAccount,如下所示:

public class GameAccount
{
    public int ID { get; private set; }
    public string Username { get; private set; }
    public string Password { get; private set; }

    public GameAccount(Account model)
    {
        this.ID = model.ID;
        this.Username = model.Username;
        this.Password = model.Password;
    }
}

......但这对我来说似乎有点无用,我确信有一种更简单的方法。

您怎么看?

2 个答案:

答案 0 :(得分:1)

您有几个选择:

选项1

使用Fruchtzwerg指示的partial课程。

选项2

您可以使用AutoMapper将项目从一种类型映射到另一种类型。这是一个例子:

// Notice the ReverseMap call. That will allow mapping in both directions.
Mapper.Initialize(cfg => 
    cfg.CreateMap<Account, GameAccount>().ReverseMap());
var account = Mapper.Map<Account>(new GameAccount());
var gameAccount = Mapper.Map<GameAccount>(account);

答案 1 :(得分:0)

Copy Constructors开发和维护成本可能非常高。通常,生成的实体框架类是部分的。

BradleyDotNET解释说:

  

生成代码时;你不希望你的其他方法/属性/被吹走,所以设计师将这些类标记为部分允许用户将其他代码放在不同的文件中。

所以可能的方法是扩展类

public partial class Account
{
    public int ID { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
}

具有其他属性,例如

public partial class Account
{
    public int SomeSpecialProperty { get; set; }
}