mvc3 entity object with extra field not saved
I am writing an mvc3 application with Entity. I am brand new to .net and entity, so this question may be basic.
I have a model in that represents an object that gets saved to the database. But I would like to have an extra field display o开发者_StackOverflow社区n the create and edit forms that is not saved to the database.
Is there a way to specify that a field is not saved with the rest of the object? Also, is there a way to make a field required on create and not on edit?
I would just hard code it, but I would like to include it in the validation that can be set on the entity models.
I am using Entity code first.
you can use viewmodels for displaying or editing, while saving map your view model to domain model(excluding the non-desired fields) and then save it. You can use a tool auto mapper
to map your view models to domain models.
say for example you have a domain class person
public class Person
{
public string Name {get; set;}
public string Address {get; set;}
}
then you make a view model
public class VMPerson
{
public string Name {get; set;}
public string Address {get; set;}
public int Age{get;set;}
}
fetch data into your view model and pass it to your view the query may look like
var q = (from p in db.Person
select new VMPerson{
Name = p.name,
Address = p.address,
Age = 16
}).SingleOrDefault();
return q;
in your view the age will also be displayed, then on post
[HttpPost]
public ActionResult Person(VMPerson vmperson)
{
Person p = new Person()// your domain object
// mapping part here
p.name = vmperson.name;
p.address = vmperson;
TryUpdateModel(p);
db.Person.Save();
}
精彩评论