【问题标题】:WCF Data Services 2 tables insert conflictWCF 数据服务 2 表插入冲突
【发布时间】:2014-11-30 16:49:54
【问题描述】:

我正在尝试使用 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

【问题讨论】:

  • 好吧,仍然-taht 与SCF 无关,而与基本- 非常基本- 数据库有关。您不能插入违反 FK 约束的行。
  • SCF?你能详细说明你想说什么吗?我正在使用 WCF 数据服务插入数据库,因此我必须使用 AddLink,但我不确定我错过了哪里。

标签: c# wcf wcf-data-services


【解决方案1】:
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。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-10
    • 1970-01-01
    • 2019-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多