2

我對ASP.NET很新,但是這是我第一個使用ASP.NET Core的應用程序。我在創建遷移後更新數據庫時遇到問題。當我鍵入命令:dotnet ef database update,我得到錯誤:「每個表中的列名必須是唯一的。」在數據庫更新期間

Column names in each table must be unique. Column name 'PortalUserId' in table 'Adverts' is specified more than once.

我認爲這個問題是我的模型結構,但我不知道我做錯了。當我用ASP.NET MVC 5進行開發時,一切正常。

這裏是我的模型(無不需要的情況下實體):

public class ApplicationDbContext : IdentityDbContext 
{ 
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) 
     : base(options) 
    { 
    } 
    public DbSet<PortalUser> PortalUsers { get; set; } 
    public DbSet<Advert> Adverts { get; set; } 
    public DbSet<Category> Categories { 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); 
    } 
} 

public class Advert 
{ 
    public int ID { get; set; } 
    public string Title { get; set; } 
    public int CategoryID { get; set; } 
    public virtual Category Category { get; set; } 
    public int PortalUserID { get; set; } 
    public PortalUser PortalUser { get; set; } 
} 

public class PortalUser : IdentityUser 
{ 
    public string FirstName { get; set; } 
    public string Surname { get; set; } 
    public ICollection<Advert> Adverts { get; set; } 

} 

我在做什麼這裏是懶加載的目的正常的虛擬映射。我將廣告字段中的FK存儲到PortalUser。

我會感謝每一個有用的答案!

我已經弄清楚,即延遲加載是不支持所以現在我的模型看起來像官方教程:

https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/new-db

public class BloggingContext : DbContext 
{ 
    public BloggingContext(DbContextOptions<BloggingContext> options) 
     : base(options) 
    { } 

    public DbSet<Blog> Blogs { get; set; } 
    public DbSet<Post> Posts { get; set; } 
} 

public class Blog 
{ 
    public int BlogId { get; set; } 
    public string Url { get; set; } 

    public List<Post> Posts { get; set; } 
} 

public class Post 
{ 
    public int PostId { get; set; } 
    public string Title { get; set; } 
    public string Content { get; set; } 

    public int BlogId { get; set; } 
    public Blog Blog { get; set; } 
} 
+0

請避免在將來強制標籤進入標題,除非它是問題/句子的自然部分,請參閱幫助中心:http://stackoverflow.com/help/tagging – Tseng

+0

您似乎有不一致的大寫。你有沒有嘗試命名屬性'PortalUserId'而不是'PortalUserID'(注意最後小寫字母D?EF Core將默認嘗試將Id添加到外鍵,如果它沒有定義,並且db列不是'你的錯誤信息顯示爲'PortalUserId',但你的模型有'PortalUserID' – Tseng

+0

我將其更改爲PortalUserId - 更新到數據庫已完成,但是在數據庫結構中我現在有PortalUserId和PortalUserId1。 。我不知道爲什麼它會發生。在MVC中,這樣的事情不會發生。 – Pawel

回答

1

好吧,夥計們,我找到了解決辦法!所有需要的是,將屬性PortalUserId的更改類型從int更改爲string。比一切編譯和沒有加倍的領域出現!

感謝您至少試圖幫助我!

相關問題