0

我使用帶有標識的ASP.NET Core並希望擴展默認的Db上下文。如果我想補充不掛表我只需添加一個新的類:向DbContext添加新實體

public partial class Table1 
{ 
    public int Id { get; set; } 
    public string Txt { get; set; } 
} 

並致以ApplicationDbContext:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser> 
{ 
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) 
     : base(options) 
    { 
    } 

    public virtual DbSet<Table1> Table1 { get; set; } 

    protected override void OnModelCreating(ModelBuilder builder) 
    { 
     base.OnModelCreating(builder); 
     // Customize the ASP.NET Identity model and override the defaults if needed. 
     // For example, you can rename the ASP.NET Identity table names and more. 
     // Add your customizations after calling base.OnModelCreating(builder); 

     builder.Entity<Table1>(entity => 
     { 
      entity.ToTable("Table_1"); 

      entity.Property(e => e.Id).HasColumnName("ID"); 

      entity.Property(e => e.Txt) 
       .IsRequired() 
       .HasMaxLength(50); 
     }); 
    } 
} 

然後創建一個遷移和更新數據庫。有用。但是,如果我想添加一個新的表,它鏈接到表從IdentityDbContext:

public partial class Users 
{ 
    public int Id { get; set; } 
    public string UserId { get; set; } 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 

    public virtual AspNetUser User { get; set; } 
} 
當然

,AspNetUser類不存在(它是由IdentityDbContext創建的,據我所知)。如何正確地做到這一點?

回答

1

該類最有可能命名爲ApplicationUser(默認)。代表此實體的表格是dbo.AspNetUsers,但由Identity設置,並且與類名稱無關。

FWIW,雖然,這是一個壞主意,以創建一個Users實體,有許多原因:

  1. 無疑會和dbo.AspNetUsersUsersApplicationUser之間的混淆,以及數據庫表dbo.Users

  2. 一般來說,您應該使用單數時態命名實體,即User,而不是Users。這個約定有很多原因,但足以說,它只是讓你的代碼更好,更易讀,可以堅持單數形式的單數形式和複數形式的複數形式。例如,ICollection<User>類型的屬性將被命名爲Users,因爲它由許多User實例組成。

  3. 你在做什麼是完全沒有必要的。 Identity存在的全部原因是Membership(ASP.NET使用的以前的身份驗證和授權框架)不允許您擴展涉及的類型。身份改變了這一切,並且在各個方面都是100%可擴展的。您可以完全訪問框架中涉及的所有實體,您可以添加並從中派生出來。如果您想爲系統中的「用戶」添加其他屬性,只需將它們直接添加到ApplicationUser類。

+0

我必須添加它,因爲它已經完成項目,基於會員供應商 –

+0

身份和會員是互相排斥的。無論是升級到身份或堅持會員。你絕對不應該試圖同時使用兩者。 –

相關問題