Reputation: 193
I am learning the usage of POCO classes and relationships between entities.
I have two tables. And I created Data Model, and POCO classes for them. But when I tried to add a new Vehicle entity and a new Journey at the same time before calling context.SaveChanges(), those two new entities will be associated automatically. That means, the new Journey record will have its VehicleId field populated with Id of the new Vehicle record.
But when I switched to entity classes generated by Data Model, that VehicleId will be null.
Here is the code I used to insert entities:
using (var context = new TravelEntities())
{
var newVehicle = new Vehicle();
newVehicle.Name = "Fly by yourself";
context.Vehicles.AddObject(newVehicle);
var newJourney = new Journey();
newJourney.Location = "Wuyishan";
context.Journeys.AddObject(newJourney);
context.SaveChanges();
}
And the POCO classes and context class:
public class Vehicle
{
public virtual int Id { get; set; }
public virtual String Name { get; set; }
public virtual ICollection<Journey> Journeys { get; set; }
}
public class Journey
{
public virtual int Id { get; set; }
public virtual String Location { get; set; }
public virtual int VehicleId { get; set; }
public virtual Vehicle Vehicle { get; set; }
}
class TravelEntities : ObjectContext
{
ObjectSet<Vehicle> _vehicles;
ObjectSet<Journey> _journeys;
public TravelEntities()
: base("name=TravelEntities", "TravelEntities")
{
_vehicles = CreateObjectSet<Vehicle>();
_journeys = CreateObjectSet<Journey>();
}
public ObjectSet<Vehicle> Vehicles { get { return _vehicles; } }
public ObjectSet<Journey> Journeys { get { return _journeys; } }
}
And following is the database schema:
create table Vehicle
(
Id int identity(1,1) primary key,
Name nvarchar(max)
)
go
create table Journey
(
Id int identity(1,1) primary key,
Location nvarchar(max),
VehicleId int,
constraint FK_Journey_Vehicle foreign key(VehicleId) references Vehicle(Id)
)
go
What I want to know is why that two new entities are associated, and how can I avoid this. Thanks for any help.
Upvotes: 0
Views: 148
Reputation: 193
All right, Slauma gave the answer in his comment, but he didn't come back. My comment for him in the question is hidden when the page is loaded, maybe he didn't see it.
The problem resides in the VehicleId property of Journey class, it should be nullable so that the default value is null for that newJourney. So I change the type of VehicleId as int? . When it is of type int, the default value is 0, which is equal to the Id value of newVehicle, I think that is the reason why they are correlated. This does not make sense, but that is how the EF works.
Upvotes: 0