修复数据为null。该方法或属性无法在零值上调用。不使用数据注释,

发布于 2025-01-19 07:47:14 字数 4119 浏览 0 评论 0原文

我试图使用实体框架检索数据库中的数据,我有表“Posts”,它有许多属性,其中一个属性是“Image”,以前不需要图像属性,所以我在“Posts”表中存储了许多记录“图像”的值为 null,现在我将“图像”更改为必需的,现在当尝试从“帖子”表检索旧记录时,asp.net 启动此异常(“数据为空。无法在 Null 上调用此方法或属性”价值观”)。

我需要什么: 我知道我可以通过从“图像”属性中删除删除[必需]注释来解决此问题,但我想保留此数据注释并检索“图像”值是否为空的所有记录。

有什么办法可以做到这一点吗?

我的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace ARID.Models
{
public class Post
{
    [Key]
    public Guid Id { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "طول العنوان يجب ان يتراوح بين 25 حرف و 100 حرف", MinimumLength = 25)]
    [Display(Name ="العنوان")]
    public string Title { get; set; }

    [Required]
    [StringLength(5000, ErrorMessage = "يجب ألا يتجاوز المحتوى عن 900 كلمة ولايقل عن 50 كلمة", MinimumLength = 50)]
   
          [Display(Name = "المحتوى")]
    public string Body { get; set; }

    [Display(Name = "تاريخ النشر")]
    [DataType(DataType.DateTime)]
    [DisplayFormat(DataFormatString = "{0:d}")]
    public DateTime DateTime { get; set; }

    [Display(Name = "السماح بالتعليقات")]
    public bool IsCommentsAllowed { get; set; }

    [StringLength(100)]
    [Display(Name = "الصورة")]
    [Required]
    public string Image { get; set; }

    [StringLength(100)]
    [Display(Name = "الملف المرفق")]
    public string File { get; set; }

    [Display(Name = "تمت الموافقة")]
    public bool IsApproved { get; set; }

    [Display(Name = "اخفاء المنشور")]
    public bool IsHidden { get; set; }

    [Display(Name = "مميز")]
    public bool IsFeatured { get; set; }

    [Display(Name = "هدية لافضل اجابة")]
    public bool IsGifted { get; set; }

    [Display(Name = "نوع الهدية")]
    public GiftType GiftType { get; set; }

    [Display(Name = "عدد القراء")]
    public int Reads { get; set; }

    [Display(Name = "حذف المنشور")]
    public bool IsDeleted { get; set; }

    [Display(Name = "المجتمع")]
    public int CommunityId { get; set; }
    [Display(Name = "المجتمع")]
    public  Community Community { get; set; }

    [Display(Name = "الناشر")]
    [StringLength(450)]
    public string ApplicationUserId { get; set; }
    [Display(Name = "الناشر")]
    public  ApplicationUser ApplicationUser { get; set; }

    [StringLength(100, ErrorMessage = "الكلمات المفتاحية قصيرة", MinimumLength = 5)]
    //[Required(ErrorMessage = "حقل الكلمات المفتاحية ضروري")]
    [Display(Name = "كلمات مفتاحية")]
    public string Tags { get; set; }

          [Display(Name = "نوع المنشور")]
    public GroupPostType PostType { get; set; }

    [Display(Name = "طلب النشر في مدونة منصة اريد")]
    public bool IsPublishRequest { get; set; }

    [Display(Name = "حالة طلب النشر")]
    public bool PublishRequestStatus { get; set; }

}

}

并在控制器中:

 public async Task<JsonResult> GetWallContents()
    {
        ARIDWallViewModel WallVM = new ARIDWallViewModel()
        {
            Posts = _context.Posts.Include(a => a.Community).Include(a => a.ApplicationUser).Where(a => a.Community.CommunityType == CommunityType.Personal && !a.IsHidden).OrderByDescending(a => a.DateTime).Take(25),
            PostComments = _context.PostComments.Include(a => a.ApplicationUser).Include(a => a.Post).OrderByDescending(a => a.DateTime).Take(25),
            Publications = _context.Publications.Include(a => a.ApplicationUser).OrderByDescending(a => a.DateOfRecord).Take(25),

            Courses = _context.Courses.Include(a=>a.ApplicationUser).OrderByDescending(a => a.DateOfRecord).Take(25),
            FreelancerReadyServices = _context.FreelancerReadyServices.Include(c => c.ApplicationUser).OrderByDescending(a => a.DateOfRecord).Take(25),
            Books = _context.Book.Include(c => c.ApplicationUser).Where(c => c.IsARIDPublications == true && c.IsFeatured == true).OrderByDescending(a => a.RecordDate).Take(25),
        };
        //ViewData["Count"] = _context.PostMetric.Count(a => a.PostId == id);
        return Json(WallVM);
    }

im trying to retrieve data form database using entity framework,i have table "Posts" which have many properties , one of these properties is "Image" , image property was not required before , so i have many stored records in "Posts" table with value null for "image", now i changed "image" to be required, now when try to retrieve old recoreds from "Posts" table asp.net launch this exception ("Data is Null. This method or property cannot be called on Null values").

what i need:
i know that i can fix this problem by remove remove [required] annotation from "image" property, but i want to keep this data annotation and retrieve all recordes weather the "image" value is Null or not Null.

is there any way to do that ?

my code:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace ARID.Models
{
public class Post
{
    [Key]
    public Guid Id { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "طول العنوان يجب ان يتراوح بين 25 حرف و 100 حرف", MinimumLength = 25)]
    [Display(Name ="العنوان")]
    public string Title { get; set; }

    [Required]
    [StringLength(5000, ErrorMessage = "يجب ألا يتجاوز المحتوى عن 900 كلمة ولايقل عن 50 كلمة", MinimumLength = 50)]
   
          [Display(Name = "المحتوى")]
    public string Body { get; set; }

    [Display(Name = "تاريخ النشر")]
    [DataType(DataType.DateTime)]
    [DisplayFormat(DataFormatString = "{0:d}")]
    public DateTime DateTime { get; set; }

    [Display(Name = "السماح بالتعليقات")]
    public bool IsCommentsAllowed { get; set; }

    [StringLength(100)]
    [Display(Name = "الصورة")]
    [Required]
    public string Image { get; set; }

    [StringLength(100)]
    [Display(Name = "الملف المرفق")]
    public string File { get; set; }

    [Display(Name = "تمت الموافقة")]
    public bool IsApproved { get; set; }

    [Display(Name = "اخفاء المنشور")]
    public bool IsHidden { get; set; }

    [Display(Name = "مميز")]
    public bool IsFeatured { get; set; }

    [Display(Name = "هدية لافضل اجابة")]
    public bool IsGifted { get; set; }

    [Display(Name = "نوع الهدية")]
    public GiftType GiftType { get; set; }

    [Display(Name = "عدد القراء")]
    public int Reads { get; set; }

    [Display(Name = "حذف المنشور")]
    public bool IsDeleted { get; set; }

    [Display(Name = "المجتمع")]
    public int CommunityId { get; set; }
    [Display(Name = "المجتمع")]
    public  Community Community { get; set; }

    [Display(Name = "الناشر")]
    [StringLength(450)]
    public string ApplicationUserId { get; set; }
    [Display(Name = "الناشر")]
    public  ApplicationUser ApplicationUser { get; set; }

    [StringLength(100, ErrorMessage = "الكلمات المفتاحية قصيرة", MinimumLength = 5)]
    //[Required(ErrorMessage = "حقل الكلمات المفتاحية ضروري")]
    [Display(Name = "كلمات مفتاحية")]
    public string Tags { get; set; }

          [Display(Name = "نوع المنشور")]
    public GroupPostType PostType { get; set; }

    [Display(Name = "طلب النشر في مدونة منصة اريد")]
    public bool IsPublishRequest { get; set; }

    [Display(Name = "حالة طلب النشر")]
    public bool PublishRequestStatus { get; set; }

}

}

and in controller:

 public async Task<JsonResult> GetWallContents()
    {
        ARIDWallViewModel WallVM = new ARIDWallViewModel()
        {
            Posts = _context.Posts.Include(a => a.Community).Include(a => a.ApplicationUser).Where(a => a.Community.CommunityType == CommunityType.Personal && !a.IsHidden).OrderByDescending(a => a.DateTime).Take(25),
            PostComments = _context.PostComments.Include(a => a.ApplicationUser).Include(a => a.Post).OrderByDescending(a => a.DateTime).Take(25),
            Publications = _context.Publications.Include(a => a.ApplicationUser).OrderByDescending(a => a.DateOfRecord).Take(25),

            Courses = _context.Courses.Include(a=>a.ApplicationUser).OrderByDescending(a => a.DateOfRecord).Take(25),
            FreelancerReadyServices = _context.FreelancerReadyServices.Include(c => c.ApplicationUser).OrderByDescending(a => a.DateOfRecord).Take(25),
            Books = _context.Book.Include(c => c.ApplicationUser).Where(c => c.IsARIDPublications == true && c.IsFeatured == true).OrderByDescending(a => a.RecordDate).Take(25),
        };
        //ViewData["Count"] = _context.PostMetric.Count(a => a.PostId == id);
        return Json(WallVM);
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

姜生凉生 2025-01-26 07:47:14

简短的答案是:不,你不能。

在您的数据库中,已经有没有图像属性集的条目,现在您已将其更改为需要,因此您的现有条目已根据新规则不再有效。因此,EF不能检索它们,因为它只是遵循您为模型设置的规则 - 此外,将属性按要求标记(且不可删除),然后如果现有条目仍将属性标记为不良的编码样式(因为您的字符串被标记为不可用的,您甚至不会收到这些空引用的编译器警告)。

因此,您必须通过迁移来修复现有条目(在添加了所需属性之后,您可能没有创建一个条目包含null的行 - 那就是为什么即使对模型进行了较小的更改,您也应该始终生成迁移的原因)。只需创建一个迁移,并将现有条目的Image属性设置为默认值。

如果您不想修改现有条目,那么您没有其他选择,只能从image> Image> image属性中删除必需属性(因为某些属性不是真正需要的实例不提供价值),并通过为image私有设置器并添加UpdateImage方法来对新条目进行验证并设置属性。

The short answer is: No you can't.

In your database there are already entries which do not have the image property set and now you have changed it to being required, so your existing entries are not valid anymore according to the new rules. Therefore EF cannot retrieve them as it just follows the rules you set up for your model - additionally it would be bad coding style to have a property being marked as required (and non-nullable) and then in case of an existing entry still getting null (you would not even get compiler warnings for these null references as your string is marked as non nullable).

Therefore you must fix existing entries through a migration (you propably haven't created one after you added the required attribute because otherwise EF would have generated a migration which changes the column in the database to "non-nullable" which would fail because of existing rows containing null - thats why you should always generate migrations even after minor changes to the model). Just create a migration and set the Image property for existing entries to a default value.

If you do not want to modify existing entries then you propably have no other choice but to remove the required attribute from the Image property (as the property is not really required if some instances do not provide a value) and do the validation for new entries yourself by making the setter for Image private and adding an UpdateImage method which validates that the new image is not empty and sets the property.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文