如何在C#MVC中更新多个模型数据 [英] How to update multiple model data in C# MVC

查看:192
本文介绍了如何在C#MVC中更新多个模型数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在创建电子商务应用程序时,我尝试从买方表更新买方及其位置表中的地址。总之,我试图使用视图模型更新多个模型。我对lamda表达式感到困惑。



加上这里的foreachloop会产生问题。

错误显示

While creating an e-commerce app I am trying to update buyer from buyer table and its address from location table. In short I am trying to update multiple models using view Model. I am confused with lamda expression.

Plus the foreachloop here is creating problem.
The error says "

An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code

Additional information: Unable to create a constant value of type 'InventorySystem.Models.Buyer'. Only primitive types or enumeration types are supported in this context.





我尝试过:



我试过了

"

What I have tried:

I have tried

var buyers = _context.Buyers.Join(_context.Locations, d => d.LocationId, o => o.id, (d, o) => new { c.Location, c.Buyer }).AsEnumerable();
            var viewModel = from l in _context.Locations
                            join b in _context.Buyers
                            on l.id equals (b.LocationId)
                            select new CustomerFormViewModel { Buyer = c.Buyer, Location = c.Location };
            foreach (var v in buyers)
            {
                v.Buyer.FName = c.Buyer.FName;
                v.Buyer.MName = c.Buyer.MName;
                v.Buyer.LName = c.Buyer.LName;
                v.Buyer.MembershipTypeId = c.Buyer.MembershipTypeId;
                v.Buyer.Verified = c.Buyer.Verified;
                v.Location.address = c.Location.address;
                v.Location.city = c.Location.city;
                v.Location.email = c.Location.email;
                v.Location.phone = c.Location.phone;
                v.Location.zipcode = c.Location.zipcode;

            }
_context.savechanges

推荐答案

var viewModel = from l in _context.Locations
                            join b in _context.Buyers
                            on l.id equals (b.LocationId)
                            select new  { Buyer = c.Buyer, Location = c.Location };
            foreach (var v in viewModel)
            {
                v.Buyer.FName = c.Buyer.FName;
                v.Buyer.MName = c.Buyer.MName;
                v.Buyer.LName = c.Buyer.LName;
                v.Buyer.MembershipTypeId = c.Buyer.MembershipTypeId;
                v.Buyer.Verified = c.Buyer.Verified;
                v.Location.address = c.Location.address;
                v.Location.city = c.Location.city;
                v.Location.email = c.Location.email;
                v.Location.phone = c.Location.phone;
                v.Location.zipcode = c.Location.zipcode;
            }
            _context.SaveChanges();//This will update your changes to the database


这篇关于如何在C#MVC中更新多个模型数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆