簡體   English   中英

代碼優先的SQL Server ASP.NET MVC6

[英]Code-First SQL Server ASP.NET MVC6

我是VB.NET程序員,但我想在業余時間學習C#和MVC。 我正在使用ASP.NET MVC 5.1.0.0,並且嘗試在SQL Server的本地實例中進行代碼優先的數據庫創建。

當我從IDE中運行Update-Database時,我能夠獲得要在數據庫中更新的第一個數據庫表,但是當我添加與第一個具有PK / FK關系的第二個表時,我在下面得到一條紅線讀取的[ForeignKey]

不包含接受1個參數的構造函數

我一直到處搜尋,卻一無所獲。 任何建議或幫助,將不勝感激。 順便說一句,第一個表是與AspNetUsers表的PK / FK關系。

 public class BuildDatabase : IdentityUser { public virtual Companies Companies { get; set; } public virtual NotaryProfile NotaryProfile { get; set; } } public class Companies { [Key] [Column("CompanyID")] // Did this as the database will reflect TableName_ColumnName instead. public int CompanyID { get; set; } public string CompanyName { get; set; } public bool IsActive { get; set; } public bool IsNotary { get; set; } public virtual ICollection<NotaryProfile> NotaryProfile { get; set; } } public class NotaryProfile { [Key] public int NotaryID { get; set; } public string NamePrefix { get; set; } public string FirstName { get; set; } public string MiddleInitial { get; set; } public string LastName { get; set; } public string NameSuffix { get; set; } public bool IsActive { get; set; } public int DefaultState { get; set; } public int DefaultCounty { get; set; } public bool IsSigningAgent { get; set; } public bool HasABond { get; set; } public decimal BondAmount { get; set; } public bool HasEandO { get; set; } public decimal EandOAmount { get; set; } public bool ElectronicNotarizationsAllowed { get; set; } public string ElectronicTechnologyUsed { get; set; } public string ComissionNumber { get; set; } public DateTime CommissionIssued { get; set; } public DateTime CommssionOriginal { get; set; } public DateTime CommissionExpires { get; set; } public DateTime CommissionFiledOn { get; set; } public string SOSAuditNumber { get; set; } public string CommissionDesc { get; set; } [Foreignkey("CompanyID")] // Companies.CompanyID = PK public int CompanyID { get; set; } // PK/FK relationship. public Companies Companies { get; set; } // Reference to Companies table above. } public class SchemaDBContext : IdentityDbContext<BuildDatabase> { public SchemaDBContext() : base("DefaultConnection"){} public DbSet<Companies> Companies { get; set; } public DbSet<NotaryProfile> NotaryProfile { get; set; } } 

您的一個類(可能是NotaryProfile )需要引用另一個對象(外鍵關系),但是該類中沒有構造函數接受參數來建立這種關系,例如:

public NotaryProfile(int companyId) {
  this.companyId = companyId;
}

順便說一句,建立這種關系的一種更好的方法是使用實​​際的類類型而不是ID,如:

public class NotaryProfile {
  ...
  public Company Company { get; set; }
  // Instead of this:
  // public int CompanyID { get; set; } // PK/FK relationship.
  ...
}

也可以看看:

C#“不包含帶有'1'參數的構造函數”

不包含帶有2個參數的構造函數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM