【问题标题】:Entity Framework asp net core relationshipEntity Framework asp net core 关系
【发布时间】:2021-03-19 17:53:35
【问题描述】:

我有两个模型: 用户:

using System.ComponentModel.DataAnnotations;

namespace EDiary.Models
{
    public class User
    {
        public int Id { get; set; }
        [Required(AllowEmptyStrings = false, ErrorMessage = "Podaj imię")]
        [MaxLength(25, ErrorMessage = "Imię jest zbyt długie. Max. 25 znaków.")]
        public string FirstName { get; set; }
        [Required(AllowEmptyStrings = false, ErrorMessage = "Podaj nazwisko")]
        [MaxLength(25, ErrorMessage = "Nazwisko jest zbyt długie. Max. 25 znaków.")]
        public string LastName { get; set; }

        [EmailAddress(ErrorMessage = "Podaj prawidłowy adres e-mail")]
        public string Email { get; set; }

        [MinLength(7, ErrorMessage = "Hasło musi składać się z conajmniej 7 znaków")]
        public string Password { get; set; }
        public Class Class { get; set; }
    }
}

和类:

using System.Collections.Generic;

namespace EDiary.Models
{
    public class Class
    {
        public int Id { get; set; }
        public User Educator { get; set; }
        public string ClassName { get; set; }
        public ICollection<User> Users { get; set; }
    }
}

当我进行添加迁移时,我收到一个错误:无法确定由“用户”类型的导航“Class.Educator”表示的关系。手动配置关系,或使用“[NotMapped]”属性或使用“OnModelCreating”中的“EntityTypeBuilder.Ignore”忽略此属性。为什么?

【问题讨论】:

    标签: c# entity-framework asp.net-core .net-core entity-framework-core


    【解决方案1】:

    将 ClassId 添加到用户:

    public class User
        {
            .....
      public int? ClassId {get; set;}
         [ForeignKey(nameof(ClassId))]
            [InverseProperty("Users")]
            public Class Class { get; set; }
        }
    

    和 EducatorId 到 Class

       public class Class
        {
            public int Id { get; set; }
           public string ClassName { get; set; }
    
             [ForeignKey("Educator")]
           public int? EducatorId {get; set;}
           public User Educator { get; set; }
          
              [InverseProperty("Class")]
            public ICollection<User> Users { get; set; }
        }
    

    【讨论】:

    • 试试这个。公共诠释?类 ID {get; set;} 你有什么错误?
    • 您是否删除了公共用户教育者 { get;放; } 从类?
    • 不,因为教育家就是教育家,我需要 ClassId 来定义学生的班级。
    • 好的,我确定了答案。
    • 我摆脱了 ICollection 用户,添加了 public int ClassId {get; set;} 并且它有效。谢谢!
    猜你喜欢
    • 2021-03-16
    • 1970-01-01
    • 2022-08-02
    • 1970-01-01
    • 1970-01-01
    • 2022-12-10
    • 2017-02-17
    • 2017-09-26
    • 1970-01-01
    相关资源
    最近更新 更多