使用从EF 4到EF 6的ExtensionMethods克隆EF实体

时间:2015-12-01 11:18:46

标签: c# entity-framework entity-framework-6 entity

我尝试使用此扩展方法克隆EF实体

    /// <summary>
    /// Extension method to Enitity Object .Cloning 
    /// Cloning the Object .If required this need to be followed by CleatEntity Objects
    /// 
    /// </summary>
    /// <param name="source">Entity Object to be cloned </param>
    /// <returns></returns>
    /// 
    public static T Clone<T>(this T source) where T : EntityObject
    {
        var obj = new System.Runtime.Serialization.DataContractSerializer(typeof(T));
        using (var stream = new System.IO.MemoryStream())
        {
            obj.WriteObject(stream, source);
            stream.Seek(0, System.IO.SeekOrigin.Begin);
            return (T)obj.ReadObject(stream);
        }
    }

用法:

var MyEntity = context.MyEntity.FirstOrDefault();
var newEntity = MyEntity.Clone(); // Here is my problem 

但MyEntity从不显示我的扩展方法,这是因为我需要将MyEntiy转换为EntityObject,但它不会直接转换。

此代码是在ef 4上运行的克隆对象的一部分。现在我的问题是如何将此代码转换为与EF 6.1一起使用?

注意:此处的完整代码为http://www.codeproject.com/Articles/137853/Cloning-the-Entity-object-and-all-related-children

0 个答案:

没有答案