ASP.NET BoilerPlate:如何从上下文中分离实体对象?

时间:2017-07-08 15:11:04

标签: aspnetboilerplate

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

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

3 个答案:

答案 0 :(得分:1)

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

2)如果您有DTO class用于保存实体,那么要克隆实体,您可以按照以下步骤操作:

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

感谢。

答案 1 :(得分: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);
        }
    }
}

答案 2 :(得分:0)

  1. 您可以在存储库中访问DbContext(不应在应用程序服务中使用DbContext)。创建自定义存储库,定义要在应用程序服务层中使用的一些方法,请参阅文档here

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