代码之家  ›  专栏  ›  技术社区  ›  Sanjeewa

实体框架不加载相关对象

  •  2
  • Sanjeewa  · 技术社区  · 6 年前

    我正在用asp.net mvc、实体框架和wcf开发音乐商店示例应用程序。

    这是一个分层应用程序,它有一个实体的公共层。

    AddToCart 行动方法 Album 对象是可以填充的,但是在wcf加载cart对象时,在cart保存之后 专辑 对象为空,可能是视图中的一些序列化问题(我不知道) @foreach (var item in Model.CartItems) 这个 item.Album.Title 变为零

    这是我的代码:

    public static void AddToCart(Album album, string ShoppingCartID)
    {
                using (MusicStoreEntities db = new MusicStoreEntities())
                {
                    // Get the matching cart and album instances
                    var cartItem = db.Carts.SingleOrDefault(
                        c => c.CartId == ShoppingCartID
                             && c.AlbumId == album.AlbumId);
    
                    if (cartItem == null)
                    {
                        // Create a new cart item if no cart item exists
                        cartItem = new Cart
                        {
                            AlbumId = album.AlbumId,
                            CartId = ShoppingCartID,
                            Count = 1,
                            DateCreated = DateTime.Now                           
                        };
    
                        db.Carts.Add(cartItem);
                    }
                    else
                    {
                        // If the item does exist in the cart, then add one to the quantity
                        cartItem.Count++;
                    }
    
                    // Save changes
                    db.SaveChanges();
                }
    }
    
    public static List<Cart> GetCartItems(string ShoppingCartID)
            {
                using (MusicStoreEntities db = new MusicStoreEntities())
                {
                   return db.Carts.Where(cart => cart.CartId == ShoppingCartID).ToList();
    
                }
            }
    

    控制器

    namespace MusicStore.Web.Controllers
    {
        public class ShoppingCartController : Controller
        {
            MusicShoppingCartMgr.Cart serviceref1 = new MusicShoppingCartMgr.Cart();
            MusicShoppingCartMgr.iShoppingCart servicemethodref1 = new iShoppingCartClient();
            //
            // GET: /ShoppingCart/
            public ActionResult Index()
            {
                var cart = ShoppingCart.GetCart(this.HttpContext);
    
                // Set up our ViewModel
                var viewModel = new ShoppingCartViewModel
                {
                    CartItems = cart.GetCartItems(cart.ShoppingCartId),
                    CartTotal = cart.GetTotal(cart.ShoppingCartId)
                };
    
                // Return the view
                return View(viewModel);
            }
            //
            // GET: /Store/AddToCart/5
    
            public ActionResult AddToCart(int id)
            {
                var addedAlbum = servicemethodref1.GetAlbum(id);
    
                // Add it to the shopping cart
                var cart = ShoppingCart.GetCart(this.HttpContext);
    
                cart.AddToCart(addedAlbum, cart.ShoppingCartId);
    
                // Go back to the main store page for more shopping
                return RedirectToAction("Index");
            }
    
    
        }
    }
    

    模型类

    namespace MusicStore.Core
    {
        [Serializable]
        [DataContract]
        public class Cart
        {
            [Key]
            [DataMember]
            public int RecordId { get; set; }
            [DataMember]
            public string CartId { get; set; }
            [DataMember]
            public int AlbumId { get; set; }
            [DataMember]
            public int Count { get; set; }
            [DataMember]
            public System.DateTime DateCreated { get; set; }
            [DataMember]
            public virtual Album Album { get; set; }
        }
    }
    
    namespace MusicStore.Core
    {
        [Serializable]
        [DataContract]
        //[Bind(Exclude = "AlbumId")]
        public class Album
        {
            [DataMember]
            [ScaffoldColumn(false)]
            public int AlbumId { get; set; }
    
            [DataMember]
            [DisplayName("Genre")]
            public int GenreId { get; set; }
    
            [DataMember]
            [DisplayName("Artist")]
            public int ArtistId { get; set; }
    
             [DataMember]
            [Required(ErrorMessage = "An Album Title is required")]
            [StringLength(160)]
            public string Title { get; set; }
    
             [DataMember]
            [Required(ErrorMessage = "Price is required")]
            [Range(0.01, 100.00,
                ErrorMessage = "Price must be between 0.01 and 100.00")]
            public decimal Price { get; set; }
    
             [DataMember]
            [DisplayName("Album Art URL")]
            [StringLength(1024)]
            public string AlbumArtUrl { get; set; }
    
               [DataMember]
             public virtual Genre Genre { get; set; }
               [DataMember]
            public virtual Artist Artist { get; set; }
             public virtual List<OrderDetail> OrderDetails { get; set; }
        }
    }
    

    数据库上下文

    namespace MusicStore.Data
    {
        public class MusicStoreEntities : DbContext
        {
            public MusicStoreEntities()
                : base("MusicStoreEntities")
            {
                var ensureDLLIsCopied = System.Data.Entity.SqlServer.SqlProviderServices.Instance;
    
                this.Configuration.ProxyCreationEnabled = false;
    
                Database.SetInitializer<MusicStoreEntities>(new CreateDatabaseIfNotExists<MusicStoreEntities>());
                Database.SetInitializer(new CommonDBInitializer());
            }
    
            public DbSet<Album> Albums { get; set; }
            public DbSet<Genre> Genres { get; set; }
            public DbSet<Artist> Artists { get; set; }
            public DbSet<Cart> Carts { get; set; }
            public DbSet<Order> Orders { get; set; }
            public DbSet<OrderDetail> OrderDetails { get; set; }
        }
    }
    

    问题是: 为什么是 专辑 对象未加载到内部 Cart 对象,以及如何修复它?

    1 回复  |  直到 6 年前
        1
  •  3
  •   sedders123 Mostafa Asadi    6 年前

    默认情况下,实体框架不会加载相关对象,以帮助防止在将一对多或多对多关系加载到内存中时出现潜在的性能问题。

    看看你发布的代码,你可能需要添加 .Include("Album") 当把购物车里的东西拿出来时 GetCartItems . 它会变成

    public static List<Cart> GetCartItems(string ShoppingCartID)
    {
        using (MusicStoreEntities db = new MusicStoreEntities())
        {
            return db.Carts.Include("Album").Where(cart => cart.CartId == ShoppingCartID).ToList();
        }
    }
    

    the Entity Framework docs 有关加载相关实体的其他选项