0

So if I want to add an artist to my website, and I create a model that holds that and some additional details like:

namespace SuperMusic.Models
{
   public artist NewArtist { get; set; }
   public IEnumerable<RecordCompanies> RecordCompanies
   {
      get { //some code to populate possible record companies }
   }

Now I can have a view to create a new artist and my model could populate a drop down of record companies that the artist can be associated with.

But in my controller, I have to define "New Artist". I believe there are two ways to do this:

newArtistModel.NewArtist = context.artist.Create();
newArtistModel.NewArtist = new artist();

Is one of these more correct than the other? Or is there actually a difference in code and one of these is incorrect?

Thanks again for answer my noob questions!

DR913
  • 119
  • 1
  • 11

2 Answers2

1

the first option newArtistModel.NewArtist = context.artist.Create(); is the correct method for creating new instances as the Context will create Entity Framework aware proxy objects.

Proxy objects provide full support for navigation properties etc.

There's a more complete answer here

Community
  • 1
  • 1
qujck
  • 14,388
  • 4
  • 45
  • 74
  • +1 for the link, but I'm still not sure what exactly sure what's happening in the background. Is it that .Create() allows access to navigation properties and new doesn't? Why wouldn't they be created when I create an instance of the object? – DR913 Jul 24 '13 at 06:13
  • @DR913 It depends on how you have defined your POCOs. Normally your navigation properties are defined with the `virtual` keyword. Having a `proxy` means that EF can override the `virtual` properties and manage navigation/lazy loading. You *can* get POCOs to work by managing navigation properties yourself when you `new` up classes (by initialising collections in your class definitions) but that's more code to achieve the same thing. You'll find plenty of questions on SO on getting navigation properties to work when `new`ing up classes. EF can get confusing enough! – qujck Jul 24 '13 at 07:24
  • I see. I guess I just haven't ran into this yet. Thanks for the help! – DR913 Jul 24 '13 at 16:54
0

This artist is being used for the view, so it is only needed to render the form. There is no need for the EF context.

So when initializing the view:

newArtistModel.NewArtist = new artist();

Then, when you post the form and want to save the artist, you will need the context and can use: context.artist.Create();

Andy T
  • 10,223
  • 5
  • 53
  • 95