WCF 数据服务 2 表插入冲突

本文关键字:插入 冲突 数据 服务 WCF | 更新日期: 2023-09-27 18:32:28

我正在尝试将 2 个表与 WCF 数据服务连接。我尝试过添加链接方法但没有成功。

例:

        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 语句与外键约束"FK_Car_Vehicle"冲突。冲突发生在数据库"DBTest",表"dbo"中。车辆","同上"一栏。

我正在关注这篇 MSDN 文章:http://msdn.microsoft.com/en-us/library/system.data.services.client.dataservicecontext.addlink%28v=vs.110%29.aspx

WCF 数据服务 2 表插入冲突

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 打开自动增量,或为此实现您自己的逻辑。例如,可以使用 Guid。