【问题标题】:LINQ to SQL deep copy object with dependencies具有依赖关系的 LINQ to SQL 深拷贝对象
【发布时间】:2009-05-20 08:58:56
【问题描述】:

我正在尝试创建一个 LINQ to SQL 对象列表,我将其添加到数据上下文中并稍后插入。当我调用 SubmitChanges() 时,虽然我收到一条错误消息,指出 WeatherForecast 对象的 Postcode 外键为空。

我似乎在调用 List.Add() 时不会对依赖对象进行深层复制。有没有办法让它做一个深拷贝?

这是我正在尝试做的一个例子。

function List<WeatherForecast> CreateForecast(Postcode postcode) 
{ 
   var forecasts = List<WeatherForecast>();

   var wf = new WeatherForecast() 
   { 
      ForecastDate = DateTime.Today
      , CurrentTemperature = (decimal)today.Attribute(XName.Get("temperature"))
   };
   wf.Postcode = postcode;

   forecasts.Add(wf); 

   ...
   Keep adding forecast objects into the list
   ...

   return forecasts;
}

【问题讨论】:

    标签: .net linq-to-sql deep-copy


    【解决方案1】:

    List.Add 根本不制作副本。假设 WeatherForecast 是一个引用类型,您只需存储对刚刚创建的 WeatherForecast 的引用。

    问题可能是您使用的 Postcode 对象尚未添加到数据库中。

    【讨论】:

      猜你喜欢
      • 2015-09-14
      • 2023-03-31
      • 1970-01-01
      • 2012-06-19
      • 2019-11-17
      • 1970-01-01
      • 1970-01-01
      • 2011-04-26
      • 1970-01-01
      相关资源
      最近更新 更多