1

如何从上下文中分离实体对象?

  1. 无法访问我的应用程序服务中的上下文
  2. 如何使用 asp.net 样板克隆一行?例如,我有行说 row1 和主键 Id 我想用新的 Id 插入相同的行内容
4

3 回答 3

1

1)您可以注入IDbContextProvider<TDbContext>您的课程并使用它的GetDbContext方法来获取DbContext.

2)如果您有一个DTO class用于保存实体,然后克隆实体,您可以按照以下步骤操作:

  • 从数据库中获取原始实体
  • 将其映射到您的实体保存 dto(我假设它不包含 Id 字段)
  • 然后将您的 dto 映射到实体
  • 保存您的实体。

谢谢。

于 2017-07-10T06:02:14.253 回答
0

您可以使用 newtonsoft 序列化:

/// <summary>
/// Perform a deep Copy of the object, using Json as a serialisation method. NOTE: Private members are not cloned using this method.
/// </summary>
/// <typeparam name="T">The type of object being copied.</typeparam>
/// <param name="source">The object instance to copy.</param>
/// <returns>The copied object.</returns>
public static T CloneJson<T>(this T source)
{            
    // Don't serialize a null object, simply return the default for that object
    if (Object.ReferenceEquals(source, null))
    {
        return default(T);
    }

    // initialize inner objects individually
    // for example in default constructor some list property initialized with some values,
    // but in 'source' these items are cleaned -
    // without ObjectCreationHandling.Replace default constructor values will be added to result
    var deserializeSettings = new JsonSerializerSettings {ObjectCreationHandling = ObjectCreationHandling.Replace};

    return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source), deserializeSettings);
}

或者你可以使用 ObjectCopier

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

/// <summary>
/// Reference Article http://www.codeproject.com/KB/tips/SerializedObjectCloner.aspx
/// Provides a method for performing a deep copy of an object.
/// Binary Serialization is used to perform the copy.
/// </summary>
public static class ObjectCopier
{
    /// <summary>
    /// Perform a deep Copy of the object.
    /// </summary>
    /// <typeparam name="T">The type of object being copied.</typeparam>
    /// <param name="source">The object instance to copy.</param>
    /// <returns>The copied object.</returns>
    public static T Clone<T>(T source)
    {
        if (!typeof(T).IsSerializable)
        {
            throw new ArgumentException("The type must be serializable.", "source");
        }

        // Don't serialize a null object, simply return the default for that object
        if (Object.ReferenceEquals(source, null))
        {
            return default(T);
        }

        IFormatter formatter = new BinaryFormatter();
        Stream stream = new MemoryStream();
        using (stream)
        {
            formatter.Serialize(stream, source);
            stream.Seek(0, SeekOrigin.Begin);
            return (T)formatter.Deserialize(stream);
        }
    }
}
于 2017-07-10T07:42:27.243 回答
0
  1. 您可以访问存储库中的 DbContext(不应在应用程序服务中使用 DbContext)。创建自定义存储库,定义一些您想在应用服务层使用的方法,请参阅此处的文档

  2. 要克隆对象,您可以在实体类中创建复制方法或使用 AutoMapper。

于 2017-07-13T02:23:22.447 回答