我正在尝试使用WCF DataServices连接2个表。 我尝试过AddLink方法但没有成功。
示例:
public Vehicle AddVehicle(VehicleModel data, List<Car> cars)
{
var vehicle =
Vehicle.CreateVehicle(
0,
data.VehicleType
data.CreatedBy
);
this.ClientRepositories
.DBContext
.AddToVehicles(vehicle);
this.AddCar(cars, vehicle);
this.ClientRepositories
.DBContext
.SaveChanges();
return vehicle;
}
public void AddCar(List<Car> cars, Vehicle vehicle)
{
foreach (var item in cars)
{
var car =
Car.CreateCar(
0,
vehicle.Id,
false
);
this.ClientRepositories
.DBContext
.AddToCars(car);
this.ClientRepositories
.DBContext
.AddLink(vehicle, "Cars", car);
// Add the new order detail to the collection, and
// set the reference to the product.
vehicle.Cars.Add(car);
car.Vehicle = vehicle;
}
}
我收到错误:
INSERT语句与FOREIGN KEY约束“FK_Car_Vehicle”冲突。冲突发生在数据库“DBTest”,表“dbo.Vehicles”,列“Id”中。
我正在关注此MSDN文章:http://msdn.microsoft.com/en-us/library/system.data.services.client.dataservicecontext.addlink%28v=vs.110%29.aspx
答案 0 :(得分:0)
public Vehicle AddVehicle(VehicleModel vehicle, IEnumerable<Car> cars)
{
using(var context = this.ClientRepositories.DBContext)
{
context.Vehicles.Add(new Vehicle()
{
Type = vehicle.VehicleType,
CreatedBy = vehicle.CreatedBy
};
foreach(var c in cars)
{
context.Cars.Add(new Car()
{
SomeBool = false,
Vehicle = vehicle
};
}
context.SaveChanges()
}
}
模型应如下所示:
public class Vehicle
{
public Vehicle()
{
this.Cars = new List<Car>();
}
public int Id {get;set;}
public string Type {get;set;}
public string CreatedBy {get;set;}
public List<Car> Cars {get;set;}
}
public class Car
{
public int Id {get;set;}
public bool SomeBool {get;set;}
public Vehicle Vehicle {get;set;}
}
启用Id的自动增量,或为此实现自己的逻辑。例如,可以使用Guids。