C# 如何使用外键关联到不同的表';身份证

C# 如何使用外键关联到不同的表';身份证,c#,database,asp.net-mvc-5,foreign-keys,C#,Database,Asp.net Mvc 5,Foreign Keys,我正在尝试制作一个购物清单应用程序,我有一个购物清单实体和一个购物清单项目实体。购物清单应该有一个ID键和一些无关紧要的额外变量。购物清单项目应该有一个ID键和一个与其购物清单ID相关的外键。我该如何做?我收到一个UpdateDatabaseException。或者,如果有更好的方法,我会很感激学习如何做到这一点 购物清单 public class ShoppingList { [Key] public int Id { get; set; } } 购物清单项目 public

我正在尝试制作一个购物清单应用程序,我有一个购物清单实体和一个购物清单项目实体。购物清单应该有一个ID键和一些无关紧要的额外变量。购物清单项目应该有一个ID键和一个与其购物清单ID相关的外键。我该如何做?我收到一个UpdateDatabaseException。或者,如果有更好的方法,我会很感激学习如何做到这一点

购物清单

public class ShoppingList
{
    [Key]
    public int Id { get; set; }
}
购物清单项目

public class ShoppingListItem
{
    [Key]
    public int Id { get; set; }

    [ForeignKey("ShoppingList")]
    public int ShoppingListId { get; set; }
{
如果你还需要上课,尽管问。我不想让这根线发胀

我得到了新的例外

"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_dbo.ShoppingListItem_dbo.ShoppingList_ShoppingListId\". The conflict occurred in database \"ShoppingListApp\", table \"dbo.ShoppingList\", column 'Id'.\r\nThe statement has been terminated."

我完全错了。你的POCO很好。错误是您试图插入主键表中不存在的外键值。

如果我认为有任何错误,请告诉我。购物列表表将有一个id(其主键)和其他列,以及一列/列表示购物列表项信息

一对多关系 代表:

ShoppingList-->ShoppingListItem1、ShoppingListItem2、ShoppingListItem3等

其中ShoppingListItem1、ShoppingListItem2等指向ShoppingListListItem表中的条目

因此,从这个角度来看,类结构应该如下所示:

public class ShoppingList
{
    [Key]
    public int Id { get; set; }

    public int ShoppingListItemId { get; set; }

    [ForeignKey("ShoppingListItemId")]
    public ShoppingListItem ShoppingListItem { get; set; }
}

public class ShoppingListItem
{
    [Key]
    public int Id { get; set; }
    //other properties
}
有关在特性上添加注释以将其标记为主键和外键的参考:

另外,如果您希望在ShoppingListItem表中有外键,并且它指向ShoppingList表,那么您面临的问题的代码和可能的更正应该是:

public class ShoppingList
{
    [Key]
    public int Id { get; set; }
    //Other Properties
}

public class ShoppingListItem
{
    [Key]
    public int Id { get; set; }
    //other properties

    public int ShoppingListId { get; set; }

    [ForeignKey("ShoppingListId")]
    public ShoppingList ShoppingList { get; set; }
}

现在我又犯了一个奇怪的错误。我将用ITI更新线程如果我有一个id为1的shoppinglist,并在该shoppinglist上创建一个新项目,该项目的FK也将为1?是的,现在我得到了DatabaseUpdateException。正在使用此线程更新线程。您试图插入主键表中不存在的外键值。这是不正确的。
ForeignKey
属性可以以任何方式应用,您只需要分别引用key属性或导航属性。换句话说,OP使用它的方式很好,因为它应用于
ShoppingListId
,但引用了
ShoppingList
@ChrisPratt。。。你是对的。我从来没有用过另一种方式抱歉我在工作,所以我无法回复。这仍然存在一个问题,即FK在基于ShoppingList的ID创建时不会自动生成