2014-11-30 1 views
0

WCF DataServices와 2 개의 테이블을 연결하려고합니다. 내가 성공하지 AddLink 방법을 시도했습니다.WCF 데이터 서비스 2 테이블에서 충돌이 발생합니다.

예 :

 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; 
     } 
    } 

나는 오류가 점점 오전 : http://msdn.microsoft.com/en-us/library/system.data.services.client.dataservicecontext.addlink%28v=vs.110%29.aspx

+0

글쎄, 아직은 SCF와는 아무런 관련이 없습니다. FK 제약 조건을 위반하는 행은 삽입 할 수 없습니다. – TomTom

+0

SCF? 무슨 말을하려고하는지 자세히 설명해 주시겠습니까? DB에 삽입하기 위해 WCF Data-Services를 사용하고 있으므로 AddLink를 사용해야합니다. 그러나 누락 된 부분을 잘 모릅니다. –

답변

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() 
    } 
} 
다음과 같이한다

모델 :

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Car_Vehicle". The conflict occurred in database "DBTest", table "dbo.Vehicles", column 'Id'.

나는이 MSDN 문서 다음되었다

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를 사용할 수 있습니다.