0

I am trying to use Model first Entity Framework in MVC4. Would like to disable the creation of some properties in the entity model, these properties only suppose to be used as a viewModel. And I will populate the model properties in the controller dynamically.

May I know what annotation attribute I should put for these properties?

If this cannot be done, then I must create a separated ViewModel to do this. However, the view model will still have other properties linked with the entity model, what is the best way to map them together? Thanks.

2 Answers 2

2

You may want to try the [NotMapped] Attribute to tell EF not to save a property. Something like:

public class MyEntity {
     public int Id {get; set;} // will be stored as a column in the DB
     [NotMapped]
     public int MyProperty {get; set;} // will not be stored as a column in the DB
}
Sign up to request clarification or add additional context in comments.

1 Comment

I tired this, it is not working with this attribute, thanks. any ot her attribute i can use?
1

Entity framework designer creates model of persisted entities. All properties added through this designer are persisted. The designer creates partial class for every modeled entity. If you want to have additional non-persisted properties available for your views you can either create your own partial part of the class for an entity with only non-persisted properties (persisted properties are already part of the autogenerated part) or you can create specialized view model with all properties you need.

2 Comments

thank you for introducing this new concept to me, though mine is using Model first approach. I think partial class only work for code first,right?
No partial class is a core concept for designer generated code since .NET 2.0 where it was introduced. With EF it is used mainly in database first and model first because with code first you don't have designer generated code = you don't need two parts of single class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.