使用相关实体更新实体框架 [英] Entity Framework Updating with Related Entity

查看:25
本文介绍了使用相关实体更新实体框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 EF 尝试使用 ASP.NET 更新实体.我正在创建一个实体,设置它的属性,然后将其传递回具有 ID 的单独层上的 EF,以便可以应用更改.我这样做是因为我只在实体绑定到 UI 控件时存储实体的 ID.

I'm using the EF to try to update an entity with ASP.NET. I'm creating an entity, setting it's properties then passing it back to the EF on a separate layer with the ID so the change can be applied. I'm doing this because I only store the ID of the entity when it's been bound to the UI controls.

一切都适用于标准属性,但我无法更新产品(相关实体)的 Category.ID.我尝试了 EntityKey、EntityReference 和其他一些,但没有保存类别 ID.这就是我所拥有的:

Everything works for standard properties, but I can't update the Category.ID of a Product (a related entity). I've tried EntityKey, EntityReference and a few other but the category ID isn't saved. This is what I have:

Product product = new Product();
product.CategoryReference.EntityKey = new EntityKey("ShopEntities.Categories", "CategoryID", categoryId);
product.Name = txtName.Text.Trim();
... other properties
StockControlDAL.EditProduct(productId, product);

public static void EditProduct(int productId, Product product) {
 using(var context = new ShopEntities()) {
     var key = new EntityKey("ShopEntities.Products", "ProductID", productId);
     context.Attach(new Product() { ProductID = productId, EntityKey = key });
     context.AcceptAllChanges();
     product.EntityKey = key;
     product.ProductID = productId;
     context.ApplyPropertyChanges("ShopEntities.Products", product);
     context.SaveChanges();
 }
}

我真的很想使用 EF,但在 ASP.NET 中使用它时似乎遇到了一些问题.

I really want to use the EF but I seem to be having a few problems with using it with ASP.NET.

推荐答案

这是这个问题的公认答案 带有实体框架的强类型 ASP.NET MVC

This is accepted answer to this question Strongly-Typed ASP.NET MVC with Entity Framework

context.AttachTo(product.GetType().Name, product);
ObjectStateManager stateMgr = context.ObjectStateManager;
ObjectStateEntry stateEntry = stateMgr.GetObjectStateEntry(model);
stateEntry.SetModified();
context.SaveChanges();

你试过了吗?

[已更新,顶部的代码不起作用]

这是我使用的小型扩展属性,因此下一个代码块更容易理解:

This is small extension property I used so next code block is easier to understand:

public partial class Product
{
    public int? CategoryID
    {
        set
        {  
           CategoryReference.EntityKey = new EntityKey("ShopEntities.Categories", "CategoryID", value);
        }
        get
        {
            if (CategoryReference.EntityKey == null)
                return null;

            if (CategoryReference.EntityKey.EntityKeyValues.Count() > 0)
                return (int)CategoryReference.EntityKey.EntityKeyValues[0].Value;
            else
                return null;
        }
    }
}

这对我有用(这次肯定):

and that worked for me (this time for sure):

System.Data.EntityKey key = new System.Data.EntityKey("ShopEntities.Products", "ProductID", productId);
        object originalItem;   

        product.EntityKey = key;
        if (context.TryGetObjectByKey(key, out originalItem))
        {
            if (originalItem is EntityObject &&
                ((EntityObject)originalItem).EntityState != System.Data.EntityState.Added)
            {
                Product origProduct = originalItem as Product;   
                origProduct.CategoryID == product.CategoryID;//set foreign key again to change the relationship status           
                context.ApplyPropertyChanges(
                    key.EntitySetName, product);

            }
        }context.SaveChanges();

肯定它看起来很老套.我认为原因是因为 EF 关系具有实体状态(修改、添加、删除),并且基于该状态,如果多对多关系发生,EF 会更改外键的值或删除行.由于某种原因(不知道为什么),关系状态没有像财产状态一样改变.这就是为什么我必须在 originalItem 上设置 CategoryReference.EntityKey 才能更改关系的状态.

For sure it's looks hacky. I think that the reason is because the EF relationships have status as entities (modified, added, deleted) and based on that status EF changes the value of foreign keys or deletes row if many to many relationship is in case. For some reason (don't know why) the relationship status is not changed the same as property status. That is why I had to set the CategoryReference.EntityKey on originalItem in order to change the status of the relationship.

这篇关于使用相关实体更新实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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