Code First中没有导航属性的映射问题 [英] Mapping problem without navigation property in Code First

查看:96
本文介绍了Code First中没有导航属性的映射问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用Code-First方案中的导航属性映射某些实体时遇到问题。令人困惑的部分是它似乎适用于INSERT但不适用于UPDATE场景。

I'm having a problem mapping some entities without using navigation propertiesin a Code-First scenario. The confusing part is that it seems to work for INSERT but not for the UPDATE scenario.

 

以下是我放在一起的一些代码说明问题。我有2个课程,费用和税费如下:

Here is some code that I put together to illustrate the problem. I have 2 classes, Fee and Tax like this:

 


  public class Fee
  {
    public int FeeId { get; set; }

    public string Name { get; set; }

    public double Amount { get; set; }

    public Tax TaxDetail { get; set; }
  }

  public class Tax
  {
    public int TaxId { get; set; }

    public string Name { get; set; }

    public double Percent { get; set; }
  }

推荐答案

嗨迈克尔,

首先,谢谢你的详细代码…它确实使我们的工作变得更容易:)

First of all, thank you for the detailed code… it definitely makes our job easier :)

因为在将tolToChange附加到最终上下文之前,feeToChange.TaxDetail为null,所以它不知道此属性已加载但已被更改为空值。例如,EF无法区分您的代码和以下内容:

Because the feeToChange.TaxDetail is null before feeToChange is attached to the final context it doesn’t know that this property was loaded but has since been changed to null. For example EF has no way of distinguishing between you code and the following:


Fee feeToChange = null;
using (FeeContext context = new FeeContext())
{
  feeToChange = context.Fees.First();
}

using (FeeContext context = new FeeContext())
{
  context.Fees.Attach(feeToChange);
  context.MarkChanged(feeToChange);

  context.SaveChanges();
}



这篇关于Code First中没有导航属性的映射问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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