实体框架将重复记录添加到与另一个具有2个外键的表相关的表中

时间:2015-10-19 14:06:34

标签: c# sql entity-framework

我正在使用自动化进行数据库优先的实体框架设置。

我有一个名为Related Items的表/模型:

public partial class tb_RelatedItem
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public tb_RelatedItem()
    {
        tb_RelatedItem1 = new HashSet<tb_RelatedItem>();
        tb_RelatedItem2 = new HashSet<tb_RelatedItem>();
    }

    [Key]
    public int RelatedItemID { get; set; }
    public byte RelatedItemTypeID { get; set; }
    public int SiteID { get; set; }
    public int SharePointItemID { get; set; }

    public virtual tb_RelatedItemType tb_RelatedItemType { get; set; }
    public virtual tb_Sites tb_Sites { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<tb_RelatedItem> tb_RelatedItem1 { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<tb_RelatedItem> tb_RelatedItem2 { get; set; }
}

然后我有另一个SQL表来跟踪RelatedItem表中两个记录之间的关系。

这是两列外键的表,没有创建为其创建的实体。

CREATE TABLE [dbo].[tb_Relationship](
[RelatedItemIDP] [int] NOT NULL,
[RelatedItemIDC] [int] NOT NULL,
CONSTRAINT [PK_tb_Relationship] PRIMARY KEY CLUSTERED 
(
    [RelatedItemIDP] ASC,
    [RelatedItemIDC] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,           
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

所以..我试图在代码中添加一个关系:

tb_RelatedItem c = GetPutRelatedItem(cItemID, cItemType, siteGUID);

using (var db = new RelatedItemsContext())
{
    //check if relationship already exists for parent
    var ris = GetRelatedItems(pItemID, pItemType, siteGUID).Where(ch => ch.ChildItemID == cItemID);

    if (ris.Count() <= 0)
    //add the relationship
    {
        //get fresh copy
        tb_RelatedItem parent = db.tb_RelatedItem.Where(u => u.RelatedItemID == p.RelatedItemID).FirstOrDefault();
        parent.tb_RelatedItem2.Add(c);

        db.SaveChanges();
    }
}

当我的代码运行以创建关系时,父值和子值被反转,并且我的子对象的副本被放在tb_RelatedItems表中。

有关如何停止重复记录的任何想法?

0 个答案:

没有答案