簡體   English   中英

Linq-to-sql POCO-由於NULL關聯而導致插入失敗

[英]Linq-to-sql POCO - insert fails because of NULL associations

我有一個表“ Location”,它與“ Site”具有外鍵關系。 我正在使用linq to sql嘗試添加新的位置記錄:

Location l = new Location
                 {
                     Description = text,
                     FloorId = 0,
                     IsCurrentLoc = false,
                     LastMove = DateTime.Now,
                     MoveId = 0,
                     SiteId = 1 
                 };

LocationTable.InsertOnSubmit(l);
LocationTable.Context.SubmitChanges();

但是,當我嘗試保存位置行時,出現此錯誤:

An attempt was made to remove a relationship between a Site and a Location. However, one of the relationship's foreign keys (Location.SiteId) cannot be set to null.

我已經設置了位置siteid(數據庫中存在站點ID 1)。

我的linq-to-sql類如下所示:

[Table(Name = "Locations")]
public class Location
{

    private List<InstallLocation> _InstallLocations = new List<InstallLocation>();


    [Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
    internal int LocationId { get; set; }

    [Association(ThisKey = "SiteId", OtherKey = "SiteId", IsForeignKey = true)]        
    public Site Site
    {
        get;
        set;
    }

    [AssociationAttribute(ThisKey = "LocationId", OtherKey = "LocationId")]
    public List<InstallLocation> InstallLocations
    {
        get
        {
            return this._InstallLocations;
        }
        set
        {
            this._InstallLocations = value;
        }
    }

}

編輯-所以我知道為什么會發生這種情況,但不知道如何解決...

多虧了這篇文章,我現在看到了發生了什么。 “站點”屬性在SiteId之前使用假名。 由於我沒有將Site設置為任何值,因此它嘗試將SiteId設置為null-這是不允許的,因此會失敗。

我不太了解的是如何使用它。 我不想從數據庫中加載Site實體,並希望通過數據庫命中來設置Site。 我有SiteId,這就是我要保留“位置”所需要的。

有任何想法嗎?

您可能需要實現Site屬性:

DeleteOnNull="true"

從此鏈接獲得:

http://blogs.msdn.com/b/bethmassi/archive/2007/10/02/linq-to-sql-and-one-to-many-relationships.aspx

找到了解決方案。

基本上,我的原始帖子很近。 我需要做的是允許我的外鍵屬性在我的課堂上可以為空。 這似乎違反直覺,因為它在數據庫中不可為空,但是L2S會將其設置為null,然后再將其設置為正確的值。

完整的工作代碼如下所示,顯示了Location與Site的關聯方式:

[Table(Name = "Locations")]
public class Location
{

    [Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
    internal int LocationId { get; set; }

    [Column]        
    public int? SiteId { get; set; }

    [Association(ThisKey = "SiteId", OtherKey = "SiteId", IsForeignKey = true)]        
    public Site Site
    {
        get;
        set;
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM