Code-First SQL Server ASP.NET MVC6

本文关键字:NET MVC6 ASP Server SQL Code-First | 更新日期: 2023-09-27 18:04:39

我是一个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; }
}

Code-First SQL Server ASP.NET MVC6

您的一个类(可能是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个参数的构造函数