如何创建新的模型实体、设置其值并保存?
我就是这样做的。它有效,但看起来很丑。我没有任何线索让它变得更有意义。 我正在使用 .NET Framework 3.5 和 MVC2
尝试解释一下... 使用以下代码,我一次又一次地将值设置为“temp”。如果表“temp”有 100 个字段,那么我必须设置值 100 次。这就是我说的丑。
//
// POST: /TableA/Create
[HttpPost]
public ActionResult Create(TableA formdata)
{
TableA temp = new TableA();
//A foreign key model in another TableB
var tbb = myDB.TableB.First(a => a.Id == formdata.TableB.Id);
temp.TableB = tbb;
//fields in this table
temp.field1= formdata.field1;
temp.field2= formdata.field2;
temp.field3= formdata.field3;
myDB.AddToTableA(temp);
myDB.SaveChanges();
return RedirectToAction("Index");
}
I do it like this. It works but looks so ugly. And I don't have any clue to make it more meaningful.
I'm using .NET Framework 3.5 and MVC2
TRY TO Explain a little more...
With the following code, I set value to 'temp' again and again. if table 'temp' have 100 fields, then I have to set value 100 times. That's what I mean ugly.
//
// POST: /TableA/Create
[HttpPost]
public ActionResult Create(TableA formdata)
{
TableA temp = new TableA();
//A foreign key model in another TableB
var tbb = myDB.TableB.First(a => a.Id == formdata.TableB.Id);
temp.TableB = tbb;
//fields in this table
temp.field1= formdata.field1;
temp.field2= formdata.field2;
temp.field3= formdata.field3;
myDB.AddToTableA(temp);
myDB.SaveChanges();
return RedirectToAction("Index");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在层中分离代码通常会有所帮助,因为您不会将 UI 与业务层或数据访问层混合在一起......如果这就是您的要求,因为很难知道您想要在您的应用程序中更改什么代码。
否则,您的代码看起来像是所有内容的混合体,变得难以维护和理解它的作用。
编辑
您可以执行以下任一操作,而不是手动设置每个属性:
使用对象初始值设定项(C# 3.0 功能)
使用实体类提供的静态工厂方法:
Separating code in layers usually helps, because you don't mix UI with business layer or data access layer... if that's what you asked, because it's rather hard to know what you's like to change in your code.
Otherwise your code looks as a mix of everything, becomes hard to maintain and understand what it does.
Edit
Instead of setting every property manually, you can do either:
Use object initializers (C# 3.0 feature)
Use static factory methods provided by entity classes: