2017-04-08 202 views
0

继承我是新来的实体框架和我在网上跟着教程创建我的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财产我可以访问所有的帐户entires在我的数据库。

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

所以,我试图做到以下几点:

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

然而,当我使用我的上下文类来获取Account对象,我不知道如何将它转换为GameAccount。我知道我可以创建一个构造函数,复制特性从AccountGameAccount,像这样:

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; 
    } 
} 

...但似乎有点inefficent给我,我敢肯定有一个简单的方法。

您认为如何?

+0

创建像'公共DbSet 游戏帐户的上下文中的另一个属性{获取;集;}'有你有所有这些行。 – dcg

+0

@dcg这是不正确的。实体框架将尝试查询名为“GameAccount”的表。 –

回答

0

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

BradleyDotNET说明:

当生成代码;你不希望你的额外的方法/属性/不管什么都消失,所以设计师将这些类标记为partial,以允许用户将其他代码放入不同的文件中。

因此,一个可能的方法是具有附加属性扩展类

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; } 
} 
+0

你几乎是对的。但在这种情况下没有代码生成,因为它是代码优先的方法。 – CodingYoshi

+0

@CodingYoshi是的,但他只是从生成的代码中给出了例子。这可能是我的解决方案 - 但是让我的类分离并仍然指定相同的名称空间似乎有点奇怪。我不能使用不同的命名空间吗? –

+0

@GilbertWilliams不,部分类必须写在同一个命名空间中(查看http://stackoverflow.com/questions/4504288/partial-class-in-different-namespaces) – Fruchtzwerg

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);