gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:35:22 25 4
gpt4 key购买 nike

我有一个 Account 类,其中包含一个 Payments 列表,其中包含一个 Products 列表,该列表是 PendingSoldRefunded

选择要付费的产品时,我可以将它们添加到付款对象中,然后将整个对象保存到 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 现在为空!?

知道我一定做错了什么吗?

编辑现在有了帐户类别:

    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; }
}

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

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);

}

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

现在保存时出现以下错误!!!

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'.

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

为清楚起见,这里是 Payment 类:

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);
}

}

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

public class Product 
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ProductID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
[DataType(DataType.Currency)]
[DisplayFormat(DataFormatString = "£{0:#,###0.00}")]
public double Price { get; set; }
[DataType(DataType.Currency)]
[Display(Name = "Total Estimated Legal Cost")]
[DisplayFormat(DataFormatString = "£{0:#,###0.00}")]
public double EstimatedTotalLegalCost { get; set; }
public virtual ICollection<Overview> Overviews { get; set; }
public virtual ICollection<Process> Processes { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime LastUpdated { get; set; }
public bool IsSelected { get; set; }
public bool IsDeleted { get; set; }
}

最佳答案

如果您查看 Entity Framework 生成的表,您会发现只有三个。给定您的数据模型,应该有将 AccountPayment 对象相互映射的联结表(同样适用于 PaymentProduct ,您可能需要对您拥有的其他集合执行相同的操作)。

关于无法将 ProductsList 转换为单个的异常是因为您的数据模型表明 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"));

这样做会指示 Entity Framework 创建联结表,允许 Payment 保存 Products 的集合。

关于c# - MVC5 EF 实体显然在保存,但在检索时为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26085594/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com