簡體   English   中英

避免表中的重復

[英]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();
                }
            }

我的數據庫中有重復的類別:

查詢結果圖片

不確定我做錯了什么,因為我嘗試從數據庫中獲取類別(如果存在)並將其放在產品上。

將 CategoryID 屬性添加到您的模型中:

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 而不是那個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM