试图添加一个实体,但也将另一个实体插入DB



我有三个实体:产品,项目(由客户购买的产品和不购买的产品组成)和以下因素:

public class Factor
{
    [Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public virtual int FactorId { get; set; }
    [Required]
    public virtual System.Guid TrackingCode { set; get; }
    [StringLength(1000)]
    public string StatusOfFactor { set; get; }
    [Required, DataType(DataType.EmailAddress), StringLength(200)]
    public string EmailOfFactor { set; get; }
    // price before discount
    public virtual double PriceOfFactor { set; get; }
    public virtual double DiscountOfFactor { set; get; }
    [StringLength(3000,MinimumLength =0)]
    public virtual string GeneralDescription { set; get; }
    public virtual List<Item> Items { set; get; }
}

public class Item
{
    //[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ItemId { set; get; }
    public int Count { set; get; }
    // 1 -> 1 relationship between product and Item
    public virtual Product Product { set; get; }
    // * -> * relationship between Item and Factor
    public virtual List<Factor> Factors { set; get; }
}

public class Product
{
    [Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public virtual int ProductId { set; get; }
    [Required]
    [StringLength(128)]
    public virtual string NameFa { set; get; }
    [Required]
    [Range(0, 990000000)]
    public virtual double Price { set; get; }
    // many->many relationship category and product
    public virtual List<Category> Categories { set; get; }
    //public virtual List<Factor> Factors { get; set; }
    public virtual Item Item { set; get; }
}

实体之间的关系如下:产品 - 项目中的1-> 1和 * -> *在项目因子

public class ProductConfig:EntityTypeConfiguration<Product>
{
    public ProductConfig() {
        // one to one relationship between product and item
        HasOptional(p => p.Item).WithRequired(i => i.Product);
    }
}

public class FactorConfig : EntityTypeConfiguration<Factor>
{
    public FactorConfig( ) {
       HasMany(p => p.Items)
      .WithMany(p => p.Factors)
      .Map(c => {
          c.ToTable("ItemsFactors");
          c.MapLeftKey("FactorID");
          c.MapRightKey("ItemID");
      });
    }
}

当我将一个因子插入DB时,另一种产品也添加到产品表中!!!这是将因子插入DB的代码:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RegisterFactor( [Bind(Include = "FactorId,TrackingCode,RegistrationDate,PaymentSucceed,PaymentIdOfBank,PaymentDate,StatusOfFactor,EmailOfFactor,TranmissionSucceed,TransmissionDate,PriceOfFactor,DiscountOfFactor,GeneralDescription,IsReturned,ReturnedDate,ReturnedDescription")]Factor factor )  
{  
    {
        // Session consist of Items and Items consist of Products
        List<Item> purchasedItems =
        (List<Item>)Session[Constants.SHOPPINGBAG];
        double totalPriceBeforeDiscount = 0.0d; 
        double totalDiscount = 0.0d;            
        double totalPriceAfterDiscount = 0.0; 
        //
        Guid trackingCode = Guid.NewGuid();
        factor.Items = new List<Item>();
        if ( purchasedItems == null )
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        foreach ( Item item in purchasedItems )
        {
            if ( item.Product != null )
            {
                factor.Items.Add(item);
            }
        }
        // allocate data to factor
        factor.PriceOfFactor = totalPriceBeforeDiscount;
        factor.DiscountOfFactor = totalDiscount;
        factor.PaymentDate = DateTime.Now;
        factor.RegistrationDate = DateTime.Now;
        factor.TrackingCode = trackingCode;
        if ( ModelState.IsValid )
        {
            //db.Factors.AsNoTracking();
            db.Products.AsNoTracking();
            db.Factors.Add(factor);
            db.SaveChanges();
            EmptyShoppingCart();
            return View("RegisterFactorSucceed", factor);
        }
        return View(factor);
    }
}

这真的很尴尬(对我来说)。为什么发生?

您的'productConfig'都在说每当项目'产品'时,都应将同样的内容添加到产品表中。这是修改的代码。

productConfig类

public class ProductConfig : EntityTypeConfiguration<Product>
{
    public ProductConfig()
    {
        // one to one relationship between product and item
        HasOptional(p => p.Item).WithOptionalDependent(i => i.Product);
    }
}

如果将项目更改为NULL,则不会添加到产品表中。

foreach (Item item in purchasedItems)
        {
            if (item.Product != null)
            {
                factor.Items.Add(item);
                item.Product = null;//Setting Product to null
            }
        }

问题可能是您的因子对象对您正在传递回EF的产品中的产品引用了一个。因此,EF将其解释为新产品,并将其与因子一起添加。

您需要任何一个..

  1. 不要将记忆中的填充产品与您添加的因素一起使用并使用IDS链接
  2. 确保您要加载要在保存之前通过跟踪将因子从数据库中附加到数据库的现有产品。

我认为https://msdn.microsoft.com/en-gb/magazine/dn166926.aspx可能会有所帮助。

相关内容

  • 没有找到相关文章

最新更新