【问题标题】:EF Code First One To ManyEF 代码第一对多
【发布时间】:2016-09-13 22:21:31
【问题描述】:

如何让一个类拥有由另一个模型组成的集合,并在我获取原始模型时填充该集合。我有一个愿望清单,该愿望清单中有 0 个或多个产品。如果我要执行 db.Wishlist.find(id),我的数据注释或流式 API 需要说什么才能填充它。这是我目前的愿望清单模型中的内容

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Models
{
    [Table("Wishlist")]
    public class Wishlist
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [ScaffoldColumn(false)]
        public int ID { get; set; }

        [StringLength(100)]
        public string Name { get; set; }

        public int ProductID { get; set; }

        public virtual ICollection<Product> Product { get; set; }

        public int CustomerID { get; set; }

        [Required]
        public Customer Customer { get; set; }

        public virtual List<Product> Products { get; set; }

        [DisplayFormat(DataFormatString = "{0:f}")]
        public DateTime CreateDate { get; set; }


        [DisplayFormat(DataFormatString = "{0:f}")]
        public DateTime LastModifiedDate { get; set; }


    }
}

将产品填充为集合或列表所需的内容。实现这一目标的正确方法是什么?我知道其中一个产品系列必须去,只是不确定需要哪些以及需要什么。

更新:添加了我的产品型号的显示。

namespace Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    [Table("Product")]
    public partial class Product
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Product()
        {
            OrderLines = new HashSet<OrderLine>();
            SKU_Table = new HashSet<Sku>();
            XREF_CatalogProduct = new HashSet<XREF_CatalogProduct>();
            ProductImages = new List<ProductImage>();
        }

        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ID { get; set; }

        [NotMapped]
        public string FormattedPrice { get { return this.Price.ToString("C"); } }

        [Required]
        [MaxLength]
        public string PageURL { get; set; }

        [Required]
        [StringLength(250)]
        public string Name { get; set; }

        [Required]
        public string Code { get; set; }

        public string Description { get; set; }

        public int CategoryID { get; set; }

        [Column(TypeName = "money")]
        [DisplayFormat(DataFormatString = "${0:#,0}", ApplyFormatInEditMode = true)]
        public decimal Price { get; set; }

        public DateTime? DateCreated { get; set; }

        public DateTime? DateModified { get; set; }

        [Required]        
        public bool Featured { get; set; }

        public virtual string ImagePath { get; set; }

        public virtual Category Category { get; set; }        

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<OrderLine> OrderLines { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Sku> SKU_Table { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<XREF_CatalogProduct> XREF_CatalogProduct { get; set; }

        public virtual ICollection<ProductImage> ProductImages { get; set; }
    }
}

【问题讨论】:

  • 你也可以展示一下你的Product 模特吗?
  • @Sampath 更新了它
  • 您是否需要了解如何与WishlistProduct 建立1 : M 关系?
  • 是的,我需要有一个愿望清单,其中没有产品或用户想要的产品数量。
  • 我认为你与WishlistProductM : M 关系没有?

标签: c# asp.net-mvc entity-framework ef-code-first data-annotations


【解决方案1】:

您必须设置M: MWishlist : Product 的关系。如果您使用DataAnnotation,代码首先将为您创建Junction table

使用数据注解:

[Table("Wishlist")]
public class Wishlist
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [ScaffoldColumn(false)]
    public int ID { get; set; }

    [StringLength(100)]
    public string Name { get; set; }

    public int CustomerID { get; set; }

    [Required]
    public Customer Customer { get; set; }

    [DisplayFormat(DataFormatString = "{0:f}")]
    public DateTime CreateDate { get; set; }


    [DisplayFormat(DataFormatString = "{0:f}")]
    public DateTime LastModifiedDate { get; set; }

    public virtual ICollection<Product> Products { get; set; }

}

    [Table("Product")]
    public partial class Product
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Product()
        {
            OrderLines = new HashSet<OrderLine>();
            SKU_Table = new HashSet<Sku>();
            XREF_CatalogProduct = new HashSet<XREF_CatalogProduct>();
            ProductImages = new List<ProductImage>();
            this.Wishlists = new HashSet<Wishlist>();

        }

        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ID { get; set; }

        [NotMapped]
        public string FormattedPrice { get { return this.Price.ToString("C"); } }

        [Required]
        [MaxLength]
        public string PageURL { get; set; }

        [Required]
        [StringLength(250)]
        public string Name { get; set; }

        [Required]
        public string Code { get; set; }

        public string Description { get; set; }

        public int CategoryID { get; set; }

        [Column(TypeName = "money")]
        [DisplayFormat(DataFormatString = "${0:#,0}", ApplyFormatInEditMode = true)]
        public decimal Price { get; set; }

        public DateTime? DateCreated { get; set; }

        public DateTime? DateModified { get; set; }

        [Required]        
        public bool Featured { get; set; }

        public virtual string ImagePath { get; set; }

        public virtual Category Category { get; set; }        

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<OrderLine> OrderLines { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Sku> SKU_Table { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<XREF_CatalogProduct> XREF_CatalogProduct { get; set; }

        public virtual ICollection<ProductImage> ProductImages { get; set; }

        public virtual ICollection<Wishlist> Wishlists { get; set; }


    }

EF查询:根据product Id检索wishlist

var prod_id=1; // your product id

var query= from wishlist in db.Wishlists
           where wishlist.Products.Any(c=>c.Product_ID== prod_id)
           select wishlist;

使用 Fluent Api :

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

        modelBuilder.Entity<Wishlist>()
                    .HasMany<Product>(s => s.Products)
                    .WithMany(c => c.Wishlists)
                    .Map(cs =>
                            {
                                cs.MapLeftKey("WishlistRefId");
                                cs.MapRightKey("ProductRefId");
                                cs.ToTable("WishlistProduct");
                            });

    }

EF查询:根据product Id检索wishlist

var prod_id=1; // your product id

var query= from wishlist in db.Wishlists
           where wishlist.Products.Any(c=>c.ProductRefId == prod_id)
           select wishlist;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多