此错误与添加迁移和更新数据库有关

问题描述 投票:0回答:1

这是下面提到的错误

已添加具有相同密钥的项目。键:[0,属性:Bulky.Models1.ShoppingCart(字典).ProductId(无字段,int?)索引器FK]

型号

using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bulky.Models1
{
    public class NewShoppingCart
    {
        public int Id { get; set; }
        
        [ForeignKey("ProductId")]
        [ValidateNever]
        public int ProductId { get; set; }
        
        public Product Product { get; set; }
        
        [Range(1, 1000, ErrorMessage = "Please enter a value between 1 to 1000")]
        public int Count { get; set; }
        
        [ForeignKey("ApplicationUserId")]
        [ValidateNever]        
        public string ApplicationUserId { get; set; }
        public ApplicationUser ApplicationUser { get; set; }
    }
}

enter image description here

我正在尝试创建表名称为 NewShoppingCart 但我在迁移过程中遇到此错误

c# entity-framework asp.net-core model-view-controller azure-sql-database
1个回答
0
投票

ForeignKey
属性可以放在“具有特定属性名称的键”或“具有特定键名称的导航属性”上
就像

        [ForeignKey("ProductId")]
        public Product Product { get; set; }

        [ForeignKey("Product")]
        public int ProductId { get; set; }

尝试以下操作:

    public class NewShoppingCart
    {
        public int Id { get; set; }


        [ValidateNever]
        public int ProductId { get; set; }

        [ForeignKey("ProductId")]
        public Product Product { get; set; }

        [Range(1, 1000, ErrorMessage = "Please enter a value between 1 to 1000")]
        public int Count { get; set; }


        [ValidateNever]
        public string ApplicationUserId { get; set; }


        [ForeignKey("ApplicationUserId")]
        public ApplicationUser ApplicationUser { get; set; }
    }

参考:https://www.entityframeworktutorial.net/code-first/foreignkey-dataannotations-attribute-in-code-first.aspx

© www.soinside.com 2019 - 2024. All rights reserved.