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