C# 实体框架-从模型继承
我是Entity Framework的新手,我已经跟随在线教程创建了我的SQL Server数据库,并制作了几个模型和一个上下文类,其中包括访问它们的属性 这是我的帐户模型:C# 实体框架-从模型继承,c#,entity-framework,C#,Entity Framework,我是Entity Framework的新手,我已经跟随在线教程创建了我的SQL Server数据库,并制作了几个模型和一个上下文类,其中包括访问它们的属性 这是我的帐户模型: public class Account { public int ID { get; set; } public string Username { get; set; } public string Password { get; set; } } 这是我的上下文类: public clas
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; }
}
但是,当我使用上下文类获取Account
对象时,我不知道如何将其转换为GameAccount
。我know我可以创建一个构造函数,将属性从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 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; }
}
您有几个选择: 选项1 使用Fruchtzwerg指示的
partial
类
选项2
可以使用将项目从一种类型映射到另一种类型。以下是一个例子:
// 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);
//注意反向映射调用。这将允许在两个方向上进行映射。
Mapper.Initialize(cfg=>
CreateMap().ReverseMap());
var account=Mapper.Map(newgameaccount());
var gameAccount=Mapper.Map(account);
在上下文中创建另一个属性,如public DbSet GameAccounts{get;set;}
这样您就有了所有这些行。@dcg这是不正确的。实体框架将尝试查询一个名为“GameCount”的表。您几乎是对的。但是在这种情况下没有代码生成,因为这是代码优先的方法。@CodingYoshi是的,但他只是从生成的代码中给出了示例。这可能是我的解决方案——但将我的类分开并仍然指定相同的名称空间似乎有点奇怪。我不能使用不同的名称空间吗?@GilbertWilliams不,必须在同一名称空间中编写一个分部类(请看)
// 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);