实体框架创建新记录,而不是“链接到”记录。现有记录 [英] Entity Framework creates new record instead of "linking to" existing record

查看:67
本文介绍了实体框架创建新记录,而不是“链接到”记录。现有记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 IdentityModels 向我的 ApplicationUser UserProperties )添加一些额外的数据。

I am using IdentityModels to add some extra data to my ApplicationUser (UserProperties).

这是UserProperties类:

Here's the UserProperties class:

    public UserProperties()
    {
        Region = new Region();
        Universe = new Universe();
    }

    public int UserPropertiesId { get; set; }
    public Region Region { get; set; }
    public Universe Universe { get; set; }

当前的问题是,每当用户创建帐户时,他们都必须选择一个区域和一个Universe,而不是将区域和Universe链接到UserProperty的条目,实体框架在Universe和Region中创建 new 整体,即使为该Area和Universe提供给AccountController的ID 是正确的(即它们存在于数据库中)。

The issue at hand is that whenever the user creates an account, they must select a region and a universe, but instead of "linking" the region and universe to the UserProperties' entries, Entity Framework creates new entires in Universes and Regions, even though the IDs supplied to the AccountController for the region and universe are correct (i.e. they exist in the DB).

我该如何解决?

如果您需要更多信息,请告诉我。

If you need any more information, please let me know.

推荐答案

您的问题出在 UserProperties 构造函数,可在其中创建 Region Universe new 实例>。这些实体将从您的数据上下文中分离出来。因此,当您调用 SaveChanges 时,实体框架看到您的用户属性具有两个分离的相关实体,它假定需要创建它们。 更多信息

Your problem is in the UserProperties constructor where you create new instances of Region and Universe. Those entities are detatched from your datacontext. Therefore when you call SaveChanges and entity framework sees that your userproperty has two detached related entities it assumes that they need to be created. More info

您需要


  1. 手动将区域和Universe附加到您的数据上下文中,例如 context.Regions.Attach (myRegion);

  2. 从数据上下文加载区域和Universe,以便将它们附加。

  3. 添加外键属性设置为 UserProperties ,然后设置它们而不是实际实体。

  1. Manually attach the region and universe to your datacontext like this context.Regions.Attach(myRegion);.
  2. Load the region and universe from the datacontext so that they are attached.
  3. Add the foreign key properties to UserProperties then set them instead of the actual entities.

我会选择3。我发现拥有可用的外键属性总是很有用的。

I would go with 3. I find that having the foreign key properties available is always useful.

您还需要从构造器中删除初始化,否则每次保存UserProperties时,它将继续创建新的区域和Universe。 <插入字符串理论笑话>

You will also need to remove the initialization from your contructor or else it will keep creating new regions and universes every time you save a UserProperties. < insert string theory joke >

这篇关于实体框架创建新记录,而不是“链接到”记录。现有记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆