在 table 中避免重复

Avoiding duplicates in table

我有 2 个实体 类、产品和类别。每个产品都有一个类别,一个类别包含许多产品:

public class Category
    {
        public int ID { get; set; }
        public string Name { get; set; }

        public Category(string name)
        {
            Name = name;
        }

        public Category()
        {
        }
    }
public class Product
    {
        public int ID { get; set; }
        public string Name { get; set; }

        public string Title { get; set; }

        public virtual Category Category { get; set; }

        public string LongDescription { get; set; }

        public string ShortDescription { get; set; }

        public string ShortSummary { get; set; }

        public string LongSummary { get; set; }

        public virtual List<ProductFeature> Features { get; set; }

        public virtual List<ProductImage> Images { get; set; }

        public double Price { get; set; }

        public virtual ProductFamily ProductFamily { get; set; }

        public virtual Series Series { get; set; }

        public virtual Supplier Supplier { get; set; }
    }

所以当我尝试像这样将它放入数据库时​​:

using (var context = new ProductContext())
            {

                try
                {
                    int count = 0;
                    foreach (Product product in products)
                    {
                        //var category = context.Categories.SingleOrDefault(x => x.Name == product.Category.Name) ?? new Category("false");
                        if (context.Categories.Any(c => c.Name == product.Category.Name))
                        {
                            var cat = context.Categories.Where(c => c.Name == product.Category.Name).FirstOrDefault();
                            product.Category = cat;
                        }
                        context.Products.Add(product);
                        count++;
                        if (count == 10) break;
                    }

                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    context.SaveChanges();
                }
            }

我的数据库中有重复的类别:

不确定我做错了什么,因为我尝试从数据库中获取类别(如果存在)并将其放在产品上。

将类别 ID 属性 添加到您的模型中:

public int? CategoryID { get; set; }

然后在循环中设置它:

var category = context.Categories.AsNoTracking().FirstOrDefault(x => x.Name == product.Category.Name);
product.CategoryID = category?.ID;

另外你不应该把context.SaveChanges()放在finally部分,因为如果发生异常,它会被称为事件,这样你就会得到一个更不清楚的异常。 还有一件事,尝试找到一种方法在您调用该方法时已经设置了 CategoryID 属性,现在您以某种方式设置 Category.Name,而不是设置 CategoryID。