MVC5 EF实体显然正在保存,但在检索时为空

时间:2014-09-28 13:55:37

标签: c# entity-framework asp.net-mvc-5

我有一个Account类,其中包含Payments列表,其中包含ProductsPending或{{1}的Sold列表}}

选择要付费的Refunded时,我可以将它们添加到Products对象中,然后将整个对象保存到Payment

但是,当我在Account操作中检索帐户时,Pay为空。

以下是Account.Payments操作:

AddProduct

public ActionResult AddProduct(List<Product> products) { //var acc = Account.FetchAccountFromIdentity(User.Identity.GetUserName()); var username = User.Identity.GetUserName(); var acc = db.Accounts.First(u => u.EmailAddress == username); var payment = new Payment(); foreach (var product in products) { if (product.IsSelected) { var tempProduct = db.Products.Find(product.ProductID); payment.Products.Add(tempProduct); payment.PaymentStatus = enPaymentStatus.Pending; payment.Gross += tempProduct.Price; payment.Vat += tempProduct.Price * 0.2; payment.Net += payment.Gross - payment.Vat; } } payment.AccountID = acc; if (acc.Payments == null) acc.Payments = new List<Payment>(); acc.Payments.Add(payment); db.SaveChanges(); return RedirectToAction("Pay", "Products", new {id = acc.AccountID} ); } 此时已正确填充任何相关付款。

然后是acc.Payments动作:

Pay

public ActionResult Pay(int? id) { var acc = db.Accounts.Find(id); var data = new AccountPaymentView { Account = acc, Payment = acc.Payments.First(p => p.PaymentStatus == enPaymentStatus.Pending) }; return View(data); } 现在为空!?

知道我一定做错了什么?

修改的 现在使用帐户类:

acc.Payments

编辑2 这是DBContext上的OnModelCreating方法(删除了不相关的部分)。我找不到一些明显的东西?

    public class Account
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int AccountID { get; set; }
        [Display(Name = "Title")]
        public string Salutation { get; set; }
        [Required]
        [Display(Name = "First Name")]
        public string FirstName { get; set; }
        [Required]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }
        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }
        [Required]
        [DataType(DataType.Password)]
        [Compare("Password", ErrorMessage = "Passwords do not match. Please try again.")]
        [Display(Name = "Confirm Password")]
        public string ConfirmPass { get; set; }
        [Required]
        [DataType(DataType.EmailAddress)]
        [Display(Name = "Email Address")]
        public string EmailAddress { get; set; }
        public virtual ICollection<Address> Addresses { get; set; }
        public virtual ICollection<Payment> Payments { get; set; }
        public DateTime CreatedOn { get; set; }
        public virtual  ICollection<DateTime> VistsList { get; set; }
        public bool IsDeleted { get; set; }
        public enAccountType AccountType { get; set; }
}

编辑3 检出Account.FetchAccountFromIdentity(),它确实打开了一个新的上下文。所以现在已经删除了,现在我在AddProduct方法中使用了一个上下文(上面更新的代码)。

现在我在保存时遇到以下错误!!!

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Properties<DateTime>()
        .Configure(c => c.HasColumnType("datetime2"));

    modelBuilder.Entity<Account>().HasOptional(x => x.Addresses).WithMany();
    modelBuilder.Entity<Account>().HasOptional(x => x.Payments).WithMany();
    modelBuilder.Entity<Payment>().HasOptional(x => x.Products).WithMany();
    modelBuilder.Entity<Payment>().HasOptional(x => x.AccountID);
    modelBuilder.Entity<Payment>().HasKey(x => x.PaymentID);

}

我尝试在OnModelCreating方法中强制PK关系,但它似乎没有帮助。

为清楚起见,这是付款类:

An object of type 'System.Collections.Generic.List`1[[PPPv2.Models.Payment, PPPv2,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' 
cannot be set or removed from the Value property of an EntityReference of type 'PPPv2.Models.Payment'.

编辑4 根据要求,这是产品型号:

public class Payment
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int PaymentID { get; set; }
    public virtual Account AccountID { get; set; }
    public virtual ICollection<Product> Products { get; set; }
    public double Gross { get; set; }
    public double Net { get; set; }
    public double Vat { get; set; }
    public string TransactionCode { get; set; }
    public enPaymentStatus PaymentStatus { get; set; }
    public bool IsDeleted { get; set; }
    public DateTime PaidOn { get; set; }

    public Payment()
    {
        Products = new List<Product>();
        Gross = 0.0;
        Net = 0.0;
        Vat = 0.0;
        IsDeleted = false;
        PaidOn = new DateTime(2000, 1, 1, 0, 0,0);
    }

}

2 个答案:

答案 0 :(得分:3)

如果查看实体框架生成的表格,您将看到其中只有三个。根据您的数据模型,应该存在将AccountPayment对象相互映射的联结表(同样适用于PaymentProduct,您很可能需要对你拥有的其他收藏品做同样的事情。)

由于您的数据模型表明List是一个集合,但数据库表是{1}},因此您无法将Products Products转换为单个实际上将其存储为PaymentProduct之间的外键(即单一实体)关系。

如果我将OnModelCreating方法中的代码更改为以下内容,则AddProducts方法将按预期工作。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Properties<DateTime>().Configure(c => c.HasColumnType("datetime2"));

    modelBuilder.Entity<Account>().HasMany(x => x.Addresses)
        .WithMany().Map(t => t.ToTable("AccountAddresses"));
    modelBuilder.Entity<Account>().HasMany(x => x.Payments)
        .WithMany().Map(t => t.ToTable("AccountPayments"));
    modelBuilder.Entity<Payment>().HasMany(x => x.Products)
        .WithMany().Map(t => t.ToTable("PaymentProducts"));
    modelBuilder.Entity<Payment>().HasOptional(x => x.AccountID);
    modelBuilder.Entity<Payment>().HasKey(x => x.PaymentID);
}

改变来自以下代码:

modelBuilder.Entity<Payment>().HasOptional(x => x.Products).WithMany();

要:

modelBuilder.Entity<Payment>().HasMany(x => x.Products).WithMany().Map(t => t.ToTable("PaymentProducts"));

这样做会指示实体框架创建允许Payment保存Products集合的联结表。

答案 1 :(得分:0)

创建付款时,您应将其直接保存到数据库中。我不认为将其添加到您的帐户对象会起作用,因为它是一个尚未被EF跟踪的实体。

public ActionResult AddProduct(List<Product> products)
{
//var acc = Account.FetchAccountFromIdentity(User.Identity.GetUserName());
var username = User.Identity.GetUserName();
var acc = db.Accounts.First(u => u.EmailAddress == username);
var payment = new Payment();

foreach (var product in products)
{
    if (product.IsSelected)
    {
        var tempProduct = db.Products.Find(product.ProductID);
        payment.Products.Add(tempProduct);
        payment.PaymentStatus = enPaymentStatus.Pending;
        payment.Gross += tempProduct.Price;
        payment.Vat += tempProduct.Price * 0.2;
        payment.Net += payment.Gross - payment.Vat;
     }
}
payment.AccountID = acc.AccountID;
db.Payments.Add(payment);
db.SaveChanges();

return RedirectToAction("Pay", "Products", new {id = acc.AccountID} );
}