我正在学习 POCO 类的用法和实体之间的关系。
我有两张桌子。我为他们创建了数据模型和 POCO 类。但是当我尝试在调用 context.SaveChanges() 之前同时添加一个新的 Vehicle 实体和一个新的 Journey 时,这两个新实体将自动关联。这意味着,新旅程记录的 VehicleId 字段将填充新车辆记录的 ID。
但是当我切换到数据模型生成的实体类时,VehicleId 将为空。
这是我用来插入实体的代码:
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();
}
还有 POCO 类和上下文类:
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; } }
}
以下是数据库架构:
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
我想知道的是为什么这两个新实体是关联的,我该如何避免这种情况。谢谢你的帮助。