Reputation: 804
Basically, I'm passing a model object to a method and in that method, assigning the proper object from the database. Since this is a reference, I assumed it would persist throughout the rest of the method in which it it was called/passed. I know this has something to do with the proxy of entity framework but can't figure out how to fix it. Here is a fragment of the code:
[HttpPost]
public ActionResult Create(NewFormViewModel nfvm)
{
db = new dbconnection(connStr);
Track track= new Track();
Track parentTrack = new Track();
this.Create_SetTrack(nfvm, track, parentTrack);
...
and then in Create_SetTrack:
private void Create_SetTrack(NewFormViewModel nfvm, Track track, Track parentTrack)
{
track = db.Tracks.FirstOrDefault();
parentTrack = db.Tracks.Where(i=>i.ParentID==track.ID).FirstOrDefault();
}
The track loads in Create_SetTrack but then, after the code after the '...' continues in Create, track is back to it's null values.
Upvotes: 0
Views: 466
Reputation: 109079
Note that a method parameter is a new variable. So you assign track
(the variable) to track
(the parameter). In the method body, the parameter is overwritten by a new reference, but the original track
(the variable) has nothing to do with that.
You are probably confused by the fact that changes you make to the same reference object will be visible outside the method body. If you'd only set a property of a new Track()
object, you'd see this value after the Create_SetTrack
call.
So I would make a method that returns the tracks, so you can assign then to the original variables. If this is an internal method, you could return a Tuple
(using Tuple
s in API methods is discouraged, because the ItemX
properties are too nondescript).
As an alternative, you could assign the tracks to another object (the view model?) that is not overwritten in the method body.
I'd prefer the first alternative though. I don't like methods that create side-effects.
Upvotes: 1
Reputation: 29243
That won't work unless you use a ref
parameter. Otherwise, the track
parameter reference will only exist in the scope of the method
private void Create_SetTrack(NewFormViewModel nfvm, ref Track track)
{
track = db.Tracks.FirstOrDefault();
}
I would advise against this, though, since it makes the code more complicated that it needs to be. A better solution is to simply return a value from the method and assign that to your variable:
private Track Create_SetTrack(NewFormViewModel nfvm)
{
return db.Tracks.FirstOrDefault();
}
[HttpPost]
public ActionResult Create(NewFormViewModel nfvm)
{
db = new dbconnection(connStr);
Track track= Create_SetTrack(nfvm);
....
Upvotes: 0