简体   繁体   中英

Error occoured while adding view in Visual Studio 2015

So I am using these classes in my application.

 public class Expenses
 {
    public Category Category { get; set; }
    public PaymentModes PaymentModes { get; set; }
 }

 public class Category 
 {
    public int CategoryID { get; set; }
    public string CategoryName { get; set; }
 }

public class PaymentModes
 {
    public int PaymentModeID { get; set; }
    public string PaymentMode { get; set; }
 }

Now when I add view in Details method it throws below error.

 public ActionResult Details(int id)
 {
    return View();
 }

在此处输入图片说明

在此处输入图片说明

What should I do?

Look at the error message. Its clearly saying that you don't primary key defined for the PaymentModes and Expenses model classes. Please write your all three model classes as follows:

public class Category 
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int CategoryID { get; set; }
    public string CategoryName { get; set; }
}

public class PaymentModes
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int PaymentModeID { get; set; }
    public string PaymentMode { get; set; }
}

public class Expenses
{
     [Key, ForeignKey("Category"),Column(Order = 0)]
     public int CategoryID { get; set; }

     [Key, ForeignKey("PaymentModes"),Column(Order = 1)]
     public int PaymentModeID { get; set; }

     public Category Category { get; set; }

     public PaymentModes PaymentModes { get; set; }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM