代码优先实体框架。急切加载,验证然后保存导致错误

问题描述 投票:0回答:1

我的设置是我有一个包含物品的篮子。物品由产品和尺寸组成。产品与尺寸有很多种关系,因此我可以验证给定尺寸对给定产品是否有效。我希望能够将项目添加到购物篮,执行一些验证并保存到数据库。

我已经创建了一个演示程序来演示我遇到的问题。程序运行时,已经有一个保存到数据库的篮子(参见DBInitializer)。它有一个项目是一个大foo。在程序中,您可以看到我装入篮子,装入小尺寸和条形产品。我把大酒吧加到了篮子里。篮子做了一些内部验证,我保存到数据库。这没有错误。

当我尝试添加具有不同大小的数据库中已存在的产品时,问题就出现了。因此,如果我们尝试向篮子添加一个大条并保存,我们会得到一个空引用异常。这不是我想要的行为,因为包含2个项目,一个大foo和一个小foo的篮子是完全有效的。

我很确定问题是因为我们已经通过急切加载已经将foo加载到篮子中。我已经尝试评论了对bossitems的热切加载,这是有效的。但是,如果可能的话,我想要一个能够保持急切负载的解决方案。

注意:我在dbcontext类中添加了一个额外的方法,即int SaveChanges(bool excludeReferenceData)。这会阻止将额外的产品和大小记录保存回数据库。我公开了所有的构造函数,getter和setter,以便更容易地复制我的问题。我的演示代码是在一个针对.net framework 4.5.2的控制台应用上创建的。 Entity框架的版本是6.2。

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using static Demo.Constants;

namespace Demo
{
    public static class Constants
    {
        public static int BasketId => 1;
        public static int SmallId => 1;
        public static int LargeId => 2;       
        public static int FooId => 1;
        public static int BarId => 2;
    }  

    public class Program
    {
        public static void Main()
        {
            using (var context = new AppContext())
            {
                var customerBasket = context.Baskets
                    .Include(b => b.Items.Select(cbi => cbi.Product))
                    .Include(b => b.Items.Select(cbi => cbi.Size))
                .SingleOrDefault(b => b.Id == BasketId);

                var size = context.Sizes.AsNoTracking()
                         .SingleOrDefault(s => s.Id == SmallId);    
                context.Configuration.ProxyCreationEnabled = false;
                var product = context
                    .Products
                    .AsNoTracking()
                    .Include(p => p.Sizes)
                    .SingleOrDefault(p => p.Id == BarId);  
                     //changing BarId to FooId in the above line results in 
                     //null reference exception when savechanges is called.

                customerBasket.AddItem(product, size);
                context.SaveChanges(excludeReferenceData: true);
            }
            Console.ReadLine();
         }
    }   

    public class Basket
    {
        public int Id { get; set; }
        public virtual ICollection<Item> Items { get; set; }

        public Basket()
        {
            Items = new Collection<Item>();
        }

        public void AddItem(Product product, Size size)
        {
            if (itemAlreadyExists(product, size))
            {
                throw new InvalidOperationException("item already in basket");
            }

            var newBasketItem = Item.Create(
              this,
              product,
              size);

            Items.Add(newBasketItem);    
        }

        private bool itemAlreadyExists(Product product, Size size)
        {
            return Items.Any(a => a.ProductId == product.Id && a.SizeId == size.Id);
        }
    }    

    public class Item
    {
        public Guid Id { get; set; }
        public int BasketId { get; set; }

        public virtual Product Product { get; set; }
        public int ProductId { get; set; }

        public virtual Size Size { get; set; }
        public int SizeId { get; set; }

        public Item()
        {

        }

        public string getDescription()
        {
            return $"{Product.Name} - {Size.Name}";
        }    

        internal static Item Create(Basket basket
            , Product product,
            Size size)
        {
            Guid id = Guid.NewGuid();

            if (!product.HasSize(size))
            {
                throw new InvalidOperationException("product does not come in size");
            }

            var basketItem = new Item
            {
                Id = id,
                BasketId = basket.Id,
                Product = product,
                ProductId = product.Id,
                Size = size,
                SizeId = size.Id
            };
            return basketItem;
        }
    }

    public class Product : IReferenceObject
    {
        public int Id { get; set; }
        public string Name { get;  set; }
        public virtual ICollection<ProductSize> Sizes { get;  set; }

        public Product()
        {
            Sizes = new Collection<ProductSize>();
        }

        public bool HasSize(Size size)
        {
            return Sizes.Any(s => s.SizeId == size.Id);
        }
    }

    public class ProductSize : IReferenceObject
    {
        public int SizeId { get;  set; }
        public virtual Size Size { get; set; }
        public int ProductId { get; set; }
    }    

    public class Size : IReferenceObject
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public class AppContext : DbContext
    {
        public DbSet<Basket> Baskets { get; set; }
        public DbSet<Product> Products { get; set; }
        public DbSet<Size> Sizes { get; set; }          

        public AppContext()
           : base("name=DefaultConnection")
        {    
            Database.SetInitializer(new DBInitializer());
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Basket>()
            .HasMany(c => c.Items)
            .WithRequired()
            .HasForeignKey(c => c.BasketId)
            .WillCascadeOnDelete(true);

            modelBuilder.Entity<Item>()
            .Property(c => c.Id)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

            modelBuilder.Entity<Item>()
            .HasKey(c => new { c.Id, c.BasketId });

            modelBuilder.Entity<ProductSize>()
                .HasKey(c => new { c.ProductId, c.SizeId });
            base.OnModelCreating(modelBuilder);

        }

        public int SaveChanges(bool excludeReferenceData)
        {
            if(excludeReferenceData)
            {
                var referenceEntries = 
                     ChangeTracker.Entries<IReferenceObject>()
                    .Where(e => e.State != EntityState.Unchanged 
                           && e.State != EntityState.Detached);

                foreach (var entry in referenceEntries)
                {
                   entry.State = EntityState.Detached;
                }
            }

            return SaveChanges();
        }
    }

    public interface IReferenceObject
    {
    }

    public class DBInitializer: DropCreateDatabaseAlways<AppContext>
    {
        protected override void Seed(AppContext context)
        {

            context.Sizes.Add(new Size { Id = LargeId, Name = "Large" });
            context.Sizes.Add(new Size { Id = SmallId, Name = "Small" });            

            context.Products.Add(
                new Product
                {
                    Id = FooId,
                    Name = "Foo",
                    Sizes = new Collection<ProductSize>()
                    {
                        new ProductSize{ProductId = FooId, SizeId = LargeId},
                        new ProductSize{ProductId = FooId, SizeId =SmallId}
                    }
                });

            context.Products.Add(new Product { Id = BarId, Name = "Bar",
                Sizes = new Collection<ProductSize>()
                    {
                        new ProductSize{ProductId = BarId, SizeId = SmallId}                        
                    }
            });

            context.Baskets.Add(new Basket
            {
                Id = BasketId,
                Items = new Collection<Item>()
                {
                    new Item
                    {
                        Id = Guid.NewGuid(),
                        BasketId =BasketId,
                        ProductId = FooId,
                        SizeId = LargeId
                    }
                }
            });    
            base.Seed(context);
        }
    } 
 }
c# entity-framework-6 ef-code-first
1个回答
1
投票

当您使用AsNoTracking时,这告诉EF不要包含正在加载到DbContext ChangeTracker中的对象。您通常希望在加载要返回的数据时执行此操作,并且知道您不想在此时将其保存。因此,我认为您只需要在所有调用中摆脱AsNoTracking,它应该可以正常工作。

© www.soinside.com 2019 - 2024. All rights reserved.