我有两个班级:公司班和复习班。 公司类包含一个评论列表。我添加了一个端点,它添加了一个评论,它也更新了公司类中的列表。但问题是列表永远不会更新,添加评论后类 Review 中的导航属性为空。
两个类的代码:
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;
}
执行结束点后结果是这样的: 审查表:
"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": []
}
找了很多也找不到问题出在哪里?!
你如何检查数据没有出现?代码看起来不错,但我会说,如果您不返回有关公司的任何信息或除了 ID 和创建的时间戳之外的评论,您的代码可以稍微简化。这条线是不必要的:
company.Reviews.Add(review);
在这种情况下相对无害,但我建议不要触及集合属性,除非您已经急切地加载了它们。
我不认为你发布的代码有问题,这可能更多的是你之后用来检查数据的代码的问题。你的公司。评论和评论。公司参考资料不是
virtual
所以延迟加载不在桌面上,这意味着如果你拉一家公司检查它的所有数据和相关评论,你需要用Include(x => x.Reveiews)
预先加载它们,如果您提取评论并希望它是公司,则相同。启用延迟加载将允许填充此数据,但会带来性能成本,这在某些情况下可能会很大,并且序列化可能会出现问题。
所以要清楚,在您的 AddReview 方法中不需要使用
Include
,而是在您加载公司并期望填充评论的地方。
如果您正在检查数据库并且没有看到正在创建/关联的记录,请在运行时仔细检查 DbContext 的连接字符串以确保它指向您期望的数据库。数据库经常被移动或对环境很重要,开发人员更新连接字符串的本地副本,但在运行时,应用程序从未更新的配置中提取连接字符串,这意味着陈旧的数据库在开发人员更新时更新正在检查不同的数据库。