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

2023-12-27

我有一个Account包含列表的类Payments,其中包含一个列表Products那是Pending, Sold or Refunded.

当选择Products要付款,我可以将它们添加到Payment对象,然后将整个对象保存到Account.

但是,当我在Pay行动,Account.Payments一片空白。

这里是AddProduct action:

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 action:

    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现在为空!?

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

Edit现在帐户类别:

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

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

如果您查看实体框架生成的表,您会发现只有三个表。给定您的数据模型,应该有映射的联结表Account and Payment互相反对(同样适用Payment and Product,并且您可能需要对您拥有的其他集合执行相同的操作)。

您遇到的关于无法投射的异常List of Products到一个是因为你的数据模型表明Products是一个集合,但数据库表实际上将其存储为之间的外键(即单个实体)关系Payment and Product.

如果我更改中的代码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();

To:

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

这样做会指示实体框架创建允许Payment收藏Products.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

MVC5 EF 实体显然正在保存,但检索时为空 的相关文章

  • ROWNUM 的 OracleType 是什么

    我试图参数化所有现有的 sql 但以下代码给了我一个问题 command CommandText String Format SELECT FROM 0 WHERE ROWNUM lt maxRecords command CommandT
  • 模板类的不明确多重继承

    我有一个真实的情况 可以总结为以下示例 template lt typename ListenerType gt struct Notifier void add listener ListenerType struct TimeListe
  • C++ 求二维数组每一行的最大值

    我已经设法用这个找到我的二维数组的每一行的最小值 void findLowest int A Cm int n int m int min A 0 0 for int i 0 i lt n i for int j 0 j lt m j if
  • C# 中值类型和引用类型有什么区别? [复制]

    这个问题在这里已经有答案了 我知道一些差异 值类型存储在堆栈上 而引用类型存储在托管堆上 值类型变量直接包含它们的值 而引用变量仅包含对托管堆上创建的对象位置的引用 我错过了任何其他区别吗 如果是的话 它们是什么 请阅读 堆栈是一个实现细节
  • 当 Cortex-M3 出现硬故障时如何保留堆栈跟踪?

    使用以下设置 基于 Cortex M3 的 C gcc arm 交叉工具链 https launchpad net gcc arm embedded 使用 C 和 C FreeRtos 7 5 3 日食月神 Segger Jlink 与 J
  • .Net Core / 控制台应用程序 / 配置 / XML

    我第一次尝试使用新的 ConfigurationBuilder 和选项模式进入 Net Core 库 这里有很多很好的例子 https docs asp net en latest fundamentals configuration ht
  • 编译的表达式树会泄漏吗?

    根据我的理解 JIT 代码在程序运行时永远不会从内存中释放 这是否意味着重复调用 Compile 表达式树上会泄漏内存吗 这意味着仅在静态构造函数中编译表达式树或以其他方式缓存它们 这可能不那么简单 正确的 他们可能是GCed Lambda
  • 我的 strlcpy 版本

    海湾合作委员会 4 4 4 c89 我的程序做了很多字符串处理 我不想使用 strncpy 因为它不会终止 我不能使用 strlcpy 因为它不可移植 只是几个问题 我怎样才能让我的函数正常运行 以确保它完全安全稳定 单元测试 这对于生产来
  • 网络参考共享类

    我用 Java 编写了一些 SOAP Web 服务 在 JBoss 5 1 上运行 其中两个共享一个类 AddressTO Web 服务在我的 ApplycationServer 上正确部署 一切都很顺利 直到我尝试在我的 C 客户端中使用
  • C 中的位移位

    如果与有符号整数对应的位模式右移 则 1 vacant bit will be filled by the sign bit 2 vacant bit will be filled by 0 3 The outcome is impleme
  • 可空属性与可空局部变量

    我对以下行为感到困惑Nullable types class TestClass public int value 0 TestClass test new TestClass Now Nullable GetUnderlyingType
  • 在 URL 中发送之前对特殊字符进行百分比编码

    我需要传递特殊字符 如 等 Facebook Twitter 和此类社交网站的 URL 为此 我将这些字符替换为 URL 转义码 return valToEncode Replace 21 Replace 23 Replace 24 Rep
  • EPPlus Excel 更改单元格颜色

    我正在尝试将给定单元格的颜色设置为另一个单元格的颜色 该单元格已在模板中着色 但worksheet Cells row col Style Fill BackgroundColor似乎没有get财产 是否可以做到这一点 或者我是否必须在互联
  • 作为字符串的动态属性名称

    使用 DocumentDB 创建新文档时 我想设置属性名称动态地 目前我设置SomeProperty 像这样 await client CreateDocumentAsync dbs db colls x new SomeProperty
  • ListDictionary 类是否有通用替代方案?

    我正在查看一些示例代码 其中他们使用了ListDictionary对象来存储少量数据 大约 5 10 个对象左右 但这个数字可能会随着时间的推移而改变 我使用此类的唯一问题是 与我所做的其他所有事情不同 它不是通用的 这意味着 如果我在这里
  • 在Linux中使用C/C++获取机器序列号和CPU ID

    在Linux系统中如何获取机器序列号和CPU ID 示例代码受到高度赞赏 Here http lxr linux no linux v2 6 39 arch x86 include asm processor h L173Linux 内核似
  • 方法参数内的变量赋值

    我刚刚发现 通过发现错误 你可以这样做 string s 3 int i int TryParse s hello out i returns false 使用赋值的返回值是否合法 Obviously i is but is this th
  • 如何在种子实体框架版本 6.x 中通过 AddOrUpdate 方法插入身份[重复]

    这个问题在这里已经有答案了 我有一个具有身份列的实体 作为数据种子的一部分 我想对系统中的 标准数据 使用特定的标识符值 我不想禁用身份 只有我想在迁移种子中设置 IDENTITY INSERT ON 我的代码是 protected ove
  • 如何在 C# 中播放在线资源中的 .mp3 文件?

    我的问题与此非常相似question https stackoverflow com questions 7556672 mp3 play from stream on c sharp 我有音乐网址 网址如http site com aud
  • 如何连接字符串和常量字符?

    我需要将 hello world 放入c中 我怎样才能做到这一点 string a hello const char b world const char C string a hello const char b world a b co

随机推荐

  • 使用控件拖动和单击对象

    现在我的场景有两个球体和一个位于 0 0 0 的点光源 使用控件 球体围绕该点旋转 但当我尝试拖动它们时 我无法让球体移动 有人可以快速看一下我的代码吗 谢谢 编辑 是的 它们会移动 但我需要它们可以独立于 THREE Controls 进
  • ESB 中有效负载的验证

    我有一个 HTTP POST REQUEST 它发送如下有效负载 键1 值1 键2 值2 键3 值3 我能够验证所有值 但每次都必须使用一个组件 在本例中 我使用了验证器 非空字符串 3 次 1 Is there any way that
  • 未找到架构 x86_64 os x lion 的符号

    当尝试使用 opencv 2 3 1 作为第三个来编译简单的 c test cpp 代码时 库 我收到以下错误消息 体系结构 x86 64 的未定义符号 cvLoadImage referenced from 这看起来像您没有正确链接到库
  • 尽管存在导入包,但 org.osgi.framework.BundleActivator 仍出现 ClassNotFoundException

    我尝试在较长一段时间后再次使用激活器运行一个非常简单的 OSGi Hello World 风格的示例 并得到 org osgi framework BundleActivator 的 ClassNotFoundException 请参阅下面
  • 逗号分隔的数组项列表

    VB NET 中是否有内置函数可以接受字符串数组并输出以逗号分隔的项目字符串 例子 function Sam Jane Bobby gt Sam Jane Bobby String Join YourArray 此外 如果您想从复选框列表
  • 参考模型编写两次迁移

    我有一个消息模型 Message 该模型作为 userTo 和 userFrom 因此有两个对 User 的引用 我该如何编写迁移 我的用户模型是User 谢谢 这是这个问题的完整答案 以防访问这个问题的人很难将所有内容放在一起 就像我第一
  • Java 静态字段初始化

    我刚刚花了半个小时弄清楚这件事 我已经设法修复了我的代码 但我不完全理解发生了什么 想知道是否有人可以阐明它 我有一个utils类型类 包含一些静态字段 例如数据库连接端点 其他程序根据手头的任务使用这些静态字段 本质上是一个图书馆 这是它
  • socket.io 私信

    我一直在网上搜索但没有运气 我正在尝试弄清楚如何将私人消息从一个用户发送到另一个用户 有很多片段 但我不确定客户端 服务器交互 如果我有要发送到的套接字的 ID 如何将其发送到服务器 以及如何确保服务器仅将消息发送到该接收者套接字 有没有人
  • ServletContextListener 不在部署时执行

    我正在尝试在部署我的战争文件时初始化流对象 我编写了一个实现 ServletContextListener 的初始化程序类 并将侦听器类标记添加到我的 web xml 中 问题是 当我向应用程序发出第一个请求时 而不是在部署应用程序时 会发
  • android:安装错误:未知失败 - 运行 apk 文件时

    昨天我在使用模拟器时没有遇到任何错误 但今天我遇到了这个错误 请检查下图 我已经运行和调试了很多次 但每次都没有得到相同的错误 安装apk文件后出现错误 请给出正确的答案 以便我可以正确修复模拟器并进行处理 现在 当我编译时 出现新错误 请
  • 用于选择性剥离 HTML 的正则表达式

    我正在尝试使用 PHP 解析一些 HTML 作为练习 将其仅作为文本输出 但我遇到了障碍 我想删除隐藏的所有标签style display none 请记住 标签可能包含其他属性和样式属性 到目前为止我的代码是这样的 page preg r
  • Windows 过滤平台 - 如何根据本地端口阻止传入连接?

    我正在尝试使用 WFP 设置一些过滤器来阻止到本地服务器的入站连接 例如 侦听端口 8080 的网络服务器 我有一个可以基于远程端口进行阻止的过滤器 因此我可以阻止我的计算机上的进程建立与端口 8080 的任何连接 但我不知道如何基于本地端
  • 您的捆绑包已锁定为 mimemagic (0.3.5),但在您的 Gemfile 中列出的任何源中都找不到该版本 [重复]

    这个问题在这里已经有答案了 今天我尝试为我的 Rails 6 1 0 构建一个带有主动存储的 docker 我收到以下错误 Your bundle is locked to mimemagic 0 3 5 but that version
  • 将 git 存储库上移一级

    Git初学者问题 我有一个小型私人网络项目 使用 msysgit 在本地进行版本控制 没有外部存储库 因为它只适合我 所以我基本上可以做任何我想做的事情 我已将其设置在项目目录中 即 webroot 中 现在必须创建第二个目录 与 webr
  • 在 Powershell 中访问音乐文件元数据[关闭]

    Closed 这个问题需要细节或清晰度 help closed questions 目前不接受答案 因此 多年来 从一台电脑 硬盘复制到另一台电脑 硬盘之间 我的音乐收藏有点混乱 所以我想以编程方式浏览每一个并更新下面屏幕截图中的文件元数据
  • 如何强制 Google Docs 从 Chrome 扩展中渲染 HTML 而不是 Canvas?

    Google 文档更新为基于画布的渲染而不是 HTML 渲染后 是否可以强制 Google 文档从 chrome 扩展而不是画布渲染 HTML 不知何故 像 Grammarly 这样的 chrome 扩展可以做到这一点 但我不完全确定如何做
  • Objective-C 和 Android [关闭]

    Closed 这个问题是基于意见的 help closed questions 目前不接受答案 我刚刚完成了一个相对较大的 Android 项目 它在我嘴里留下了一种苦涩的味道 因为我知道它永远不会在太阳系这一边最普遍的手机之一上运行 那个
  • Blazor recaptcha 验证属性 IHttpContextAccessor 始终为 null

    我想尝试一下使用 Blazor 服务器端 到目前为止 我已经设法以某种方式克服了大多数令人头疼的问题 并且很享受它 直到现在 我正在尝试为 Google Recaptcha v3 编写一个验证器 它需要用户的 IP 地址 通常我会通过以下方
  • C# Sql 连接驱动程序

    SQL 连接对象连接到 SQL Server 以运行查询的驱动程序是什么 如果我有以下代码 SQLConnection cn new SqlConnection server ServerName initial catalog Corpo
  • MVC5 EF 实体显然正在保存,但检索时为空

    我有一个Account包含列表的类Payments 其中包含一个列表Products那是Pending Sold or Refunded 当选择Products要付款 我可以将它们添加到Payment对象 然后将整个对象保存到Account