2

Entity-Frameworks我在使用POCO实体时遇到问题。我在产品和类别之间有关系,我有以下代码要保存在数据库中:

    public virtual void Add(T entity)
    {
        ContextEntity.AddObject(entity);
        Context.SaveChanges();
    }

我正在尝试使用已经存在的类别创建一个新产品,但是当我查询数据库时,新产品与一个新类别的关系与我尝试关联的前一个类别具有相同的值。我一直在寻找答案,但这些示例不适用于我,因为我没有他们在示例中使用的相同方法。也许是因为我正在使用POCO实体,我不确定。

4

2 回答 2

1

I've made a few assumptions about your code but maybe one of these methods will help.

  1. When creating the new Product instance you can set the foreign key value like CategoryId to the existing Category Id

  2. If you want to set the navigation property "Product.Category" you must make sure of the following:

The referenced Category instance must be owned by the context by either using the Context.Categories.Attach or by first fetching it through the context with e.g. Context.Categories.FirstOrDefault(c => c.id == 1)

If you set Product.Category equal to a disconnected instance of Category the context will automatically try and add the referenced instance.

于 2012-08-28T06:33:55.543 回答
0
    [HttpPost]
    public ActionResult Create(CategoriaView collection)
    {
        try
        {
            UnidadDeMedida unidadDeMedida= 
                unidadDeMedidaService.GetByCriteria(i => i.IdUnidadDeMedida == collection.UnidadDeMedida.IdUnidadDeMedida)
                .FirstOrDefault();
            Mapper.CreateMap<UnidadDeMedida,UnidadDeMedidaView>();
            Mapper.CreateMap<UnidadDeMedidaView,UnidadDeMedida>();
            UnidadDeMedidaView unidadDeMedidaView =
                Mapper.Map<UnidadDeMedida,UnidadDeMedidaView>(unidadDeMedida);
            collection.UnidadDeMedida = unidadDeMedidaView;
            Mapper.CreateMap<CategoriaView, Categoria>();

            Categoria categoria =
                Mapper.Map<CategoriaView, Categoria>(collection);
            categoria.UnidadDeMedida = unidadDeMedida;
            service.Add(categoria);

            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }
于 2012-08-28T19:38:13.603 回答