如何将实体对象与上下文分离?

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

===============>>#1 票数:1

1)您可以将IDbContextProvider<TDbContext>注入到您的类中,并使用其GetDbContext方法获取DbContext

2)如果您具有用于保存实体的DTO class ,则可以使用以下步骤克隆实体:

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

谢谢。

===============>>#2 票数: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);
        }
    }
}

===============>>#3 票数:0

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

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

  ask by Nitin Sawant translate from so

未解决问题?本站智能推荐: