2013-01-21 39 views
0

我是LINQ to SQL中的新用戶,我使用它有一些問題。 我已經使用了LINQ to SQL Designer,並創建了我的類,映射到數據庫表上。 特別是,我有一個類,命名聲音:在嵌套字段中插入

[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.voce")] 
public partial class voce : INotifyPropertyChanging, INotifyPropertyChanged 
{ 

    private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty); 

    private int _id_voce; 

    ... other private fields; 



    private int _category; 

    private EntityRef<category> _category1; 
      public voce() 
    { 
     this._riepilogo = new EntitySet<riepilogo>(new Action<riepilogo>(this.attach_riepilogo), new Action<riepilogo>(this.detach_riepilogo)); 
     this._hera = default(EntityRef<hera>); 
     this._category1 = default(EntityRef<category>); 
     OnCreated(); 
    } 

    [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_id_voce", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)] 
    public int id_voce 
    { 
     get 
     { 
      return this._id_voce; 
     } 
     set 
     { 
      if ((this._id_voce != value)) 
      { 
       this.Onid_voceChanging(value); 
       this.SendPropertyChanging(); 
       this._id_voce = value; 
       this.SendPropertyChanged("id_voce"); 
       this.Onid_voceChanged(); 
      } 
     } 
    } 

    ...... 
    [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_category", DbType="Int NOT NULL")] 
    public int category 
    { 
     get 
     { 
      return this._category; 
     } 
     set 
     { 
      if ((this._category != value)) 
      { 
       if (this._category1.HasLoadedOrAssignedValue) 
       { 
        throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException(); 
       } 
       this.OncategoryChanging(value); 
       this.SendPropertyChanging(); 
       this._category = value; 
       this.SendPropertyChanged("category"); 
       this.OncategoryChanged(); 
      } 
     } 
    } 

正如你所看到的,幾句類有一個字段中指定的類別,是指一臺名爲類別。

當我添加一個新的幾句到我的數據庫,我創建了一個新的幾句istance和使用的DataContext,我只需添加它,使用:

voce v = new voce(){...field, category1 = //create or retrieve category}; 

特別是,類別字段從檢索數據庫如果已經存在,或者如果不存在,則在我插入語音之前插入它。

的問題是,當我添加了語音數據庫:

datacontext.InsertOnSubmit(v); 
datacontext.SubmitChanges(); 

再次插入類,具有獨特的contraint失敗。

如何在不添加任何嵌套對象的情況下添加語音?

謝謝你,對不起我的英文不好。

+0

我覺得這個問題可能在'//創建或檢索類別'。它可能總是創建新的類別,或者不會將返回的類別返回到當前的'datacontext'。你可以發佈該方法的代碼嗎? – mipe34

回答

0
internal category GetCategoryFromDescription (string desc, Utility.VOICE_MODALITY mode) 
    { 
     bool type = mode == Utility.VOICE_MODALITY.ENTRATA ? true : false; 
     var query = from cat in dc.category 
        where cat.description == desc && cat.type == type 
        select cat; 

     if (query.Count() == 0) 
     { 
      category newC = new category() { description = desc }; 
      dc.category.InsertOnSubmit(newC); 
      dc.SubmitChanges(); 
      return newC; 
     } 
     else 
      return query.Single(); 

    }