【发布时间】:2017-09-04 00:29:02
【问题描述】:
我是 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;
}
}
...但这对我来说似乎有点低效,我相信还有更简单的方法。
你怎么看?
【问题讨论】:
-
在上下文中创建另一个属性,例如
public DbSet<GameAccount> GameAccounts {get;set;},然后您将拥有所有这些行。 -
@dcg 这是不正确的。实体框架将尝试查询名为“GameAccount”的表。
标签: c# entity-framework