【发布时间】:2022-01-17 02:35:02
【问题描述】:
我必须构建一个访问现有数据库表的 .net Web 应用程序。
数据库为不同的公司使用不同的表:公司“ACorp”中的客户存储在表“ACorpCustomers”中,公司“B”中的客户存储在表“BCorpCustomers”中。
使用 ADO .NET 实体模型,我为每个公司创建了不同的 Db 上下文:
public partial class ACorpContext : DbContext
{
public ACorpContext()
: base("name=ACorpContext")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<ACorpCustomer> ACorpCustomers { get; set; }
}
}
edmx 也生成类
public partial class ACorpCustomer
{
public string Name { get; set; }
public string Phone { get; set; }
}
我创建了一个父类 Customer 以在应用程序中使用,具有相同的属性:
public class ACorpCustomer
{
public virtual string Name { get; set; }
public virtual string Phone { get; set; }
}
我还没有找到让特定实体 ACorpCustomers 从父客户继承的方法; edmx 返回继承错误,但无法覆盖属性。
更新
为了避免使用edmx文件,我最后试了一下:
-
我使用 AutomaticMigrationsEnabled 参数禁用了 __MigrationHistory sql 表创建:
internal sealed class Configuration : DbMigrationsConfiguration<MyDomain.Models.ACorpContext> { public Configuration() { AutomaticMigrationsEnabled = false; } } -
我在 App.config 文件设置中禁用了数据库初始化 disableDatabaseInitialization="true"
-
然后我添加了一个 ADO .NET 实体模型,但选择了“首先来自数据库的代码”。 为了确保不改变模型中的数据库,我禁用了数据库初始化器:
public ACorpContext() : base("name=ACorpContext") { Database.SetInitializer<ACorpContext>(null); }
现在我希望我的职责是使域模型与数据库保持同步。 无论如何,我确信如果发生错位,不会尝试修改数据库。 如果没有 edmx,我在定义从抽象类 Customer 继承时就没有更多限制了。
无论如何,我无法理解为什么 Visual Studio 认为这是“代码优先”的方法。
【问题讨论】:
标签: c# .net entity-framework inheritance