2011-01-07 106 views
1

我有一个与“站点”有外键关系的表“位置”。我使用的LINQ to SQL尝试添加一个新的位置记录:Linq-to-sql POCO - 由于NULL关联导致插入失败

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到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进行presendese。由于我没有设置网站的任何东西,它试图将SiteId设置为空 - 这是不允许的,因此它失败。

我不明白的是如何处理这个。我不想从数据库加载Site实体,只需设置数据库即可设置网站。我有SiteId,这是我为了坚持我的“地点”所需要的。

任何想法?

回答

0

找到这个解决方案。

基本上,我原来的贴子很接近。我需要做的是让我的外键属性在我的班级中可以为空。这似乎与直觉相反,因为它在数据库中不可空,但是L2S将其设置为空,然后才将其设置为正确值。

完整的工作代码如下所示,显示位置如何与站点相关联:

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

} 
相关问题