0

我正在 razor web 应用程序 (asp.netcore) 中开发一个应用程序,并使用 efcore 搭建 db 表。

我在我的 OnlineForms 数据表上执行了一个 db-scaffold,它创建了我的 OnlineForms.cs 类。当我直接将 [key] 属性放在此类中的 formid 属性之上时,我可以毫无问题地保存到数据表中。

但是当我通过[ModelMetadataType]属性将[key]数据注释移动到引用OnlineForms的部分类OnlineFormsValidation中时,我尝试保存数据;我收到错误消息:“实体类型 'OnlineForm' 需要定义主键。”

必需的注释在 OnlineFormsValidation 类中正常工作,但 [Key] 注释不能。

先感谢您。任何帮助将不胜感激。

OnlineForm.cs:

namespace VehicleTakeHomeApp.Data.Models
{
   public partial class OnlineForm {
       [Key] <== works if i put it here, but I want to move it to OnlineFormValidation.cs
       public int FormId { get; set; }
       public string EmployeeId { get; set; }
       public string Name { get; set; }
   }
}

OnlineFormValidation.cs:

using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;

namespace VehicleTakeHomeApp.Data.Models
{

    [ModelMetadataType(typeof(OnlineFormValidation))]
    public partial class OnlineForm
    {
    }

    public class OnlineFormValidation
    {
        [Key]  <== this annotation is not getting picked up, even though the Required annotations below it get picked up.
        public int FormId { get; set; }

        [Required(ErrorMessage = "Employee ID is required.")]
        public string EmployeeId { get; set; }

        [Required(ErrorMessage = "Name is required.")]
        public string Name { get; set; }
    }
}
4

1 回答 1

0

我将 dbcontext 类中的 OnModelCreating 方法注释掉了。此方法包含来自初始 db-scaffold 的 HasKey()。

我取消了 OnModelCreating 方法的注释,现在我不需要将 [Key] 注释添加到任一类并且它可以工作。

它更像是一种解决方法,而不是一种解决方案,但它的工作原理。

于 2020-07-13T18:45:54.973 回答