Linq-to-sql POCO - 由于NULL关联而导致插入失败

时间:2011-01-07 14:27:54

标签: c# linq-to-sql

我有一个“位置”表,它与“站点”有外键关系。我正在使用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;
        }
    }

}

编辑 - 所以我知道为什么会这样,但不知道如何修复它......

感谢this帖子,我现在看看发生了什么。 “Site”属性需要通过SiteId进行主题化。由于我没有将Site设置为任何东西,它试图将SiteId设置为null - 这是不允许的,因此它失败了。

我不太明白的是如何使用它。我不想从数据库中加载Site实体,只是为了设置Site而进行数据库命中。我有SiteId,这就是我需要的所有才能坚持我的“位置”。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

您可能需要在网站资源上实施:

DeleteOnNull="true"

从此链接获得:

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

答案 1 :(得分:0)

找到解决方案。

基本上,我原来的帖子很接近。我需要做的是允许我的外键属性在我的班级中可以为空。这似乎是违反直觉的,因为它在数据库中不可为空,但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;
    }

}