.net 添加< Reviews>新审查时列表未更新

6tqwzwtp  于 2023-03-24  发布在  .NET
关注(0)|答案(1)|浏览(98)

我有两个类:公司和一个Review类。公司类包含一个列表Reviews。我添加了一个端点,它添加了一个Review,它也更新了公司类中的列表。但问题是列表永远不会更新,并且在添加Review后,Review类中的导航属性为null。
这两个类的代码:

public class Company
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int CompanyId { get; }
        [MaxLength(100)]
        public string CompanyName { get; set; } = string.Empty;
        [MaxLength(500)]
        public string CompanyDescription { get; set; } = string.Empty;
        [MaxLength(100)]
        public string Location { get; set; } = string.Empty;
        [MaxLength(50)]
        public string City { get; set; } = string.Empty;
        [MaxLength(50)]
        public string Category { get; set; } = string.Empty;
        [MaxLength(400)]
        public string PhotoUrl { get; set; }
        public List<Review> Reviews { get; set; } = new List<Review>();
    }
public class Review
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ReviewId { get; set; }
        [Required,MaxLength(70)]
        public string JobTitle { get; set; } = string.Empty;
        [Required, MaxLength(1000)]
        public string Content { get; set; } = string.Empty;
        public DateTime TimeCreated { get; set; } = DateTime.UtcNow;
        public int TotalUpvotes { get; set; } = 0;
        public ApplicationUser User { get; set; }
        public string UserId { get; set; }
        public Company Company { get; set; }
        public int CompanyId { get; set; }
}

OnModelCreating中两个表的配置:对于公司表:

builder.HasKey(c => c.CompanyId);

            builder.HasMany(c=>c.Reviews)
                .WithOne(c => c.Company)
                .HasForeignKey(c => c.CompanyId);

对于审查表:

builder.HasKey(r => r.ReviewId);
            builder.HasOne(r=>r.User)
                .WithMany(r=>r.Reviews)
                .HasForeignKey(r=>r.UserId)
                .OnDelete(DeleteBehavior.ClientCascade);
            builder.HasOne(r => r.Company)
                .WithMany(r => r.Reviews)
                .HasForeignKey(r => r.CompanyId)
                .OnDelete(DeleteBehavior.ClientCascade);

添加新审阅服务:

public async Task<ServiceResponse<AddReviewResponseDto>> AddReview(AddReviewDto addReviewDto)
ServiceResponse<AddReviewResponseDto> AddReviewResponse = new ServiceResponse<AddReviewResponseDto>();

            //check if the current user is registered in the database
            var user = await _userManager.FindByIdAsync(GetUserId());

            if (user == null)
            {
                AddReviewResponse.Data = null;
                AddReviewResponse.Success = false;
                AddReviewResponse.Message = "Non Users can't add a review!";
                return AddReviewResponse;
            }

            var company = await _context.Companies.SingleOrDefaultAsync(c => c.CompanyId == addReviewDto.CompnayId);
            if (company == null)
            {
                AddReviewResponse.Data = null;
                AddReviewResponse.Success = false;
                AddReviewResponse.Message = "No company was found with this id!";
                return AddReviewResponse;
            }

           
            var review = new Review
            {
                JobTitle = addReviewDto.JobTitle,
                Content = addReviewDto.Content,
                User = user,
                Company = company

            };

            await _context.AddAsync(review);

            company.Reviews.Add(review);

            await _context.SaveChangesAsync();
            var addReviewResponseDto = new AddReviewResponseDto
            {
                TimeCreated = review.TimeCreated,
                ReviewId = review.ReviewId
            };

            AddReviewResponse.Data = addReviewResponseDto;
            AddReviewResponse.Success = true;
            AddReviewResponse.Message = "Review was added successfully";
            return AddReviewResponse;

}

执行完end Point后,结果如下:对于审查表:

"reviewId": 14,
    "jobTitle": "software engineer",
    "content": "I Love This Company",
    "timeCreated": "2023-03-23T18:54:04.7119397",
    "totalUpvotes": 0,
    "user": null,
    "userId": "userIdvalue",
    "company": null,
    "companyId": 6,
    "upvotes": []

对于公司表:

{
    "companyId": 6,
    "companyName": "Globe Exports",
    "companyDescription": "We Globe exportsare exporters of canned products, pasta, flour, biscuits, jams, honey, tahina, halawa, foul, tomato puree, biscuits, wafer,spices&bean.",
    "location": "Cairo, Egypt",
    "city": "Cairo",
    "category": "Food Industries",
    "photoUrl": "photoUrl",
    "reviewsCount": 0,
    "averageRating": 0,
    "reviews": []
}

我找了很多,也找不到问题出在哪里?!

hi3rlvi2

hi3rlvi21#

如何检查数据是否出现?代码看起来很好,尽管我想说,考虑到您没有返回任何关于公司或评论的信息,除了ID和创建的时间戳之外,您的代码可以稍微简化。这一行是不必要的:

company.Reviews.Add(review);

在这种情况下,它相对无害,但我建议不要触及集合属性,除非您已经急切地加载了它们。
我不认为你发布的代码有问题,可能更多的是你用来检查数据的代码的问题。你的公司。评论和评论。公司引用不是virtual,所以懒惰加载不在表中,这意味着如果你拉一个公司来检查它的所有数据和相关评论,你需要用Include(x => x.Reveiews)来加载它们,启用延迟加载将允许填充此数据,但会带来性能成本,在某些情况下可能会很大,并且可能会出现序列化问题。
因此,需要说明的是,在AddReview方法中不必使用Include,而是在加载Company并期望填充评论的情况下使用。
如果您正在检查数据库,但没有看到正在创建/关联的记录,然后在运行时仔细检查DbContext的连接字符串,以确保它指向您期望的数据库。通常,数据库被移动或对环境很重要,开发人员更新了连接字符串的本地副本,但在运行时,应用程序正在从配置中拉取连接字符串,而该配置不是“t updated意味着当开发人员检查不同的数据库时,陈旧的数据库得到更新。

相关问题