插入提交与关联

时间:2014-08-25 10:34:46

标签: c# .net sql-server linq-to-sql

我正在使用LinqToSql在Winforms C#应用程序中映射我的数据库。

到目前为止,绑定看起来很好,但是两个表之间的关系存在问题。

它是一种记录对象历史记录的记录器。在每个日志事件上都有一个外键链接到导致该事件的对象。问题是每次我在日志中创建一行时,在另一个表中创建一个具有新ID的新对象。我只想将现有对象与现有ID一起使用。

将对象插入数据库

 System.Data.Linq.Table<History> history = dataContext.GetTable<History>();
 History h = new History()
 {
      ReadTime = DateTime.Now,
      MyObject = o
 };

 // The "MyObject" is a reference to an existing object.
 history.InsertOnSubmit(h); 

 // OnSubmit a new MyObject is created with a new ID,
 // instead of referencing the existing one.
 history.Context.SubmitChanges(); 

模型类

[Table(Name = "tbl_History")]
public class History : INotifyPropertyChanged
{
    private long m_HistoryID;
    private int m_MyObjectFK;
    private EntityRef<MyObject> m_MyObject = new EntityRef<MyObject>();
    private DateTime m_ReadTime;

    [Column(IsPrimaryKey = true, IsDbGenerated = true, Name = "HistoryID")]
    public long HistoryID
    {
        get { return this.m_HistoryID; }
        set { this.m_HistoryID = value; }
    }

    [Column(Storage="m_MyObjectFK")]
    public int MyObjectFK 
    {
        get { return this.m_MyObjectFK; }
        set { this.m_MyObjectFK= value; } 
    }

    [Association(Name = "FK_tbl_History_tbl_MyObject",
    IsForeignKey = true, Storage = "m_MyObject", ThisKey = "MyObjectFK")]
    public MyObject MyObject
    {
        get { return m_MyObject.Entity; }
        set 
        { 
            m_MyObject.Entity = value;
            NotifyPropertyChanged("MyObject");
        }
    }

    [Column(Name = "ReadTime", DbType = "DateTime", CanBeNull = false)]
    public DateTime ReadTime
    {
        get { return m_ReadTime; }
        set
        {
            m_ReadTime = value;
            this.NotifyPropertyChanged("ReadTime");
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我已经解决了这个问题。之所以会发生这种情况,是因为我要引用的对象来自其他DataContext。在这种情况下,它被识别为新对象。在关联中使用它之前,必须将其重新附加到DataContext

新代码

System.Data.Linq.DataContext dataContext = new System.Data.Linq.DataContext(connection);

dataContext.GetTable<MyObject>().Attach(o); // Add this line and reattach the MyObject o.

System.Data.Linq.Table<History> history = dataContext.GetTable<History>();

在此链接下回答了类似的问题。

Why is LINQ to SQL entity association creating a new (duplicate) row when inserting a new record?