我必須構建一個訪問現有資料庫表的 .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 從父 Customer 繼承的方法;edmx 回傳繼承錯誤,但無法覆寫屬性。
uj5u.com熱心網友回復:
你的定義
public partial class ACorpCustomer
與繼承無關。partial是 .NET 版主,表示您的類定義是更大定義的一部分。例如,如果您將班級拆分為 2 個代碼檔案。.Net 將它們“組合”在一起,最終得到一個type
在這里你似乎需要做的是
public abstract class Customer
{
public string Name { get; set; }
public string Phone { get; set; }
}
public class ACorpCustomer : Customer
{
// may be, some unique properties here
}
public class BCorpCustomer : Customer
{
// may be, some unique properties here
}
屬性Name和Phone甚至都不需要是virtual。回顧你的頭銜,沒有什么是你需要的override。我什么都沒看到。。
uj5u.com熱心網友回復:
這在 Code-First 中是微不足道的,您可以(并且應該)與現有資料庫一起使用。只需將單個 Customer 物體映射到每個 DbContext 的正確表:
public partial class ACorpContext : MyBaseDbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>().ToTable("ACorpContext");
}
public virtual DbSet<Customer> Customers{ get; set; }
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/381344.html
