Entity Framework代码优先:如何添加与现有实体相关的实体?

时间:2018-11-10 07:18:01

标签: c# .net entity-framework entity-framework-6

有一个Products表。每个产品都有评论列表。添加产品时,最初它们没有评论。我正在尝试通过在产品内部添加List<Review>来对现有产品进行评论,但会引发错误

  

违反多重性约束

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; }
    }
}

Review.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; }
    }
}

添加新产品的方法

public Product Add(Product product)
{
    using (var context = new ShopDbContext())
    {
        context.Database.Log = Console.WriteLine;
        var response = context.Products.Add(product);
        context.SaveChanges();
        return response;
    }
}

添加新评论的方法

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 p = new Product
{
    Catagory = Catagory.COMPUTER,
    Name = "Surface Pro 3",
    Description = "Tablet / Laptop",
    Specification = "i5 16 GB ram",
};


productService.Add(p);

添加新评论:

Review review = new Review
{
    Customer = customerService.Get(1),
    Product = productService.Get(1),
    Stars = 2,
    Text = "It's a good camera",
};

productService.AddReview(1, review);

引发此错误

  

System.InvalidOperationException:'违反多重性约束。关系'DatabaseProject.Review_Product'的角色'Review_Product_Target'具有多重性1或0..1。'

编辑

对不起,我忘了提这个。

我还有一个Customer表,其中存储了该客户的一组评论。这是由某种原因引起的错误吗?

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; }
    }
}

enter image description here

0 个答案:

没有答案