0

I was encountring an error when I try to add class to the database

DB.Trips.Add(trip);

I solved it by setting the navigation properties to null, but i never had to do that before and it worked just fine, so im wondering why is that, as it doesnt seem to me as a good approach and the problem might persist.

When I do the DB.SaveChanges(); I get an error. From the SQL profiler I found out that it is trying to insert a record into Countries table.

exec sp_executesql N'insert [dbo].[Countries](......

But Trips table doesn't even have Country property. There is a City property, which has Country. But why would it try to add that as well and how can I force it to insert only into Trips table ?

The data comes in via angular $http.post, is it possible its somehow related ?

Trip class city related attributes

 public int CityOriginID { get; set; }
 public int CityDestinationID { get; set; }    
 public virtual City CityDestination { get; set; }
 public virtual City CityOrigin { get; set; }

City class

public partial class City
{
    public int CityID { get; set; }
    public string Name { get; set; }
    public string CountryCode { get; set; }

    public virtual Country Country { get; set; }
}

Thanks for any suggestions

1 Answer 1

1

Try adding a reference to your Trip entity in your City entity like

public virtual ICollection<Trip> Trips {get; set;} 

to indicate your one-to-many relationship

Sign up to request clarification or add additional context in comments.

2 Comments

I had it like that - navigation properties in my entity data model, but then I got problems with Json serializing. In the view im using angularJS, but the error is when i return JSON from the controller. this is the error. Self referencing loop detected with type 'System.Data.Entity.DynamicProxies.Trip_1521F4589BD8DFB07BA950E05E4B6029B3E847C1CAB6F4F1F8DCBAE7C9EF8544'. Path 'tripsList[0].cityDestination.tripsDestination'.
@user3549969 hmmm, try adding another reference just like the one above. public virtual ICollection<Trip> Trips1 {get; set;} Now, you should have two collections of Trip

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.