【发布时间】:2019-04-13 20:16:53
【问题描述】:
一个产品可以有多个评论。评论由单个客户进行。 因此,review 具有 Customer 和 Product 作为属性。
产品.cs
namespace DatabaseProject.Models
{
public class Product
{
public Product()
{
Reviews = new List < Review >();
}
public int Id { get; set; }
public Catagory Catagory { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Specification { get; set; }
public List<Review> Reviews { get; set; }
}
}
评论.cs
namespace DatabaseProject.Models
{
public class Review
{
public int Id { get; set; }
public string Text { get; set; }
public int Stars { get; set; }
[Required]
public Product Product { get; set; }
[Required]
public Customer Customer { get; set; }
}
}
客户.cs
namespace DatabaseProject.Models
{
public class Customer
{
public Customer()
{
Addresses = new List<Address>();
Reviews = new List<Review>();
}
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public List<Address> Addresses { get; set; }
public List<Review> Reviews { get; set; }
}
}
添加新评论的方法。
我将它添加到产品表的评论列表中。
public bool AddReview(int id, Review review)
{
using (var context = new ShopDbContext())
{
Product oldProduct = context.Products.Find(id);
if (oldProduct == null)
{
return false;
}
oldProduct.Reviews.Add(review);
context.SaveChanges();
return true;
}
}
添加新评论
在这里,由于评论已添加到 product.Reviews 我不必传递产品属性。
但我必须通过客户。不知何故,这创造了一个新客户,而不是引用现有客户。
productService.AddReview(1,
new Review
{
Customer = customerService.Get(1),
Stars = 2,
Text = "It's a good camera",
});
这会导致客户表中出现重复条目。
【问题讨论】:
标签: c# asp.net .net entity-framework entity-framework-6