保存新记录实体框架时出现C#错误

时间:2013-03-01 14:20:06

标签: c# sql-server-2008 entity-framework

我在sql中有表格

 USE [testDB]
 GO

 /****** Object:  Table [dbo].[MemberPanel]    Script Date: 03/01/2013 19:21:01 ******/
 SET ANSI_NULLS ON
 GO

 SET QUOTED_IDENTIFIER ON
 GO

 CREATE TABLE [dbo].[MemberPanel](
[UserId] [uniqueidentifier] NOT NULL,
[PanelId] [int] NOT NULL,
[Status] [int] NOT NULL,
  CONSTRAINT [PK_MemberPanel] PRIMARY KEY CLUSTERED 
 (
[UserId] ASC,
[PanelId] ASC
 )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
 ) ON [PRIMARY]

 GO

 ALTER TABLE [dbo].[MemberPanel]  WITH CHECK ADD  CONSTRAINT [FK_MemberPanel_Member]      FOREIGN KEY([UserId])
 REFERENCES [dbo].[Member] ([UserId])
 GO

 ALTER TABLE [dbo].[MemberPanel] CHECK CONSTRAINT [FK_MemberPanel_Member]
 GO

 ALTER TABLE [dbo].[MemberPanel]  WITH CHECK ADD  CONSTRAINT      [FK_PracticePanel_PracticePanel] FOREIGN KEY([PanelId])
 REFERENCES [dbo].[Panel] ([PanelId])
 GO

 ALTER TABLE [dbo].[MemberPanel] CHECK CONSTRAINT [FK_PracticePanel_PracticePanel]
 GO

我使用实体框架并使用c#代码作为

 public static bool AddMemberPanels(List<int> panelIDs, Guid userId, int status)
    {
        try
        {
            using (FairShareEntities fairShareEntities = new FairShareEntities())
            {
                foreach (var panelID in panelIDs)
                {
                    var panel = new MemberPanel() { UserId = userId, PanelId = panelID,      Status = status };
                    fairShareEntities.AddToMemberPanel(panel);
                    fairShareEntities.SaveChanges();
                }

                return true;
            }
        }
        catch (Exception)
        {
            return false;
        }

    }
保存时

通过错误

更改它
      {"Entities in 'TestEntities.MemberPanel' participate in the                'FK_MemberPanel_Member' relationship. 0 related 'Member' were found. 1 'Member' is expected."}

请在这里帮助我我不知道为什么它不允许我添加新记录,我还检查所有值,即UserID和PanelId,是的,它们存在于那些表中作为PK。

提前致谢

4 个答案:

答案 0 :(得分:1)

不知道这是否是确切问题,但在EF中,通常不应设置外键ID。相反,您应该从数据库中提取用户和Panel实体,并将新的MemberPanel实体的导航属性设置为它们......

var newMemberPanel = ... // as you have already
newMemberPanel.Panel = existingPanel;
newMemberPanel.User = existingUser;

我认为这可能会更好。

此外,您最好使用上下文中的方法创建新实体,而不是单独创建它,然后将其添加到上下文中。我发现这有时是一种更稳定的方法。你应该可以做这样的事情......

 var newMemberPanel = ctx.MemberPanels.Add();

...然后按照我上面的说明继续进行。

希望这有帮助

答案 1 :(得分:0)

这是外键错误。这是一个SQL错误而不是实体框架错误。

在添加“MemberPanel”之前,您需要添加“Member”对象。

您的数据库shema指定了这个:

    ADD CONSTRAINT [FK_MemberPanel_Member] FOREIGN KEY([UserId]) 
    REFERENCES [dbo].[Member] ([UserId])

因此指定的UserId需要在表Member

然后使用不带ID的实体

var myLovedUser = fairShareEntities.Members.Where(x=>x.UserId = userID);
var incrediblePanel =  fairShareEntities.Panels.Where(x=>x.PanelId = panelId);
var memberPanel = new MemberPanel() {User = myLovedUser, Panel=incrediblePanel, Status= status };
fairShareEntities.AddToMemberPanel(panel);
fairShareEntities.SaveChanges();

答案 2 :(得分:0)

我已经解决了这个问题,感谢每一个人:

 public static bool AddMemberPanels(List<int> panelIDs, Guid memberId, int status)
    {
        try
        {
            using (FairShareEntities fairShareEntities = new FairShareEntities())
            {
                foreach (var panelId in panelIDs)
                {
                    //get the member and panels
                    Member theMember =
                        (from m in fairShareEntities.Member.Include("MemberPanel") where m.UserId == memberId select m).FirstOrDefault();

                    //see if this Member is already on this Panel
                    if (!(from mp in theMember.MemberPanel where mp.PanelId == panelId select mp).Any())
                    {

                        //get the panel
                        Panel thePanel = (from p in fairShareEntities.Panel where p.PanelId == panelId select p).FirstOrDefault();

                        //add the panel to this Member
                        MemberPanel addMemberPanel = new MemberPanel()
                        {
                            UserId = memberId,
                            Status = status,
                            Panel = thePanel,
                            PanelId = panelId
                        };
                        theMember.MemberPanel.Add(addMemberPanel);
                        fairShareEntities.SaveChanges();
                    }
                }

                return true;
            }
        }
        catch (Exception)
        {
            return false;
        }

    }

答案 3 :(得分:0)

sig A { }
sig X {
  name: set A
  }

fun get [a:A] : set X{
    ((X <: name) :> a).A
}

fun get' [a:A] : set X{
    name.a
}

check {
  all a: A | get[a] = get'[a]
}