简体   繁体   English

在对象之间复制值

[英]Copy values between objects

I am writing a utility to copy specific data from a backend SQL database to a client computers SQL Express database. 我正在编写一个实用程序,用于将特定数据从后端SQL数据库复制到客户端计算机SQL Express数据库。 The backend database and the client database are identical. 后端数据库和客户端数据库是相同的。 The data are for surveyors that go to remote sites without network. 数据适用于没有网络就可以到达远程站点的测量师。 I am using a REST service and using Entity Framework both on the Service and on the proxy. 我正在使用REST服务,并且在服务和代理上都使用了Entity Framework。 I am copying the property values with this code: 我使用以下代码复制属性值:

private void GatherFrom<TSelf, TSource>(TSelf self, TSource source)
{
    PropertyInfo[] sourceAllProperties = source.GetType().GetProperties();

    foreach (PropertyInfo sourceProperty in sourceAllProperties)
    {
        PropertyInfo selfProperty = self.GetType().GetProperty(sourceProperty.Name);
        if (selfProperty.CanRead
            && (selfProperty.GetSetMethod(true) != null && !selfProperty.GetSetMethod(true).IsPrivate)
            && (selfProperty.GetSetMethod().Attributes & MethodAttributes.Static) == 0
            && selfProperty.PropertyType.IsAssignableFrom(sourceProperty.PropertyType))
        {
            var sourceValue = sourceProperty.GetValue(source);
            selfProperty.SetValue(self, sourceValue);
        }
    }
}

This works all fine. 一切正常。

But when I apply the new data: 但是当我应用新数据时:

Surveys newSurvey = new Surveys();

GatherFrom(newSurvey, survey);

localSurveys.Add(newSurvey);

I get into problems because I have ambiguous types from remote and local in the same namespace. 我遇到了问题,因为在同一个名称空间中,远程和本地的类型不明确。

Any idea how to split it up? 知道如何拆分吗?

You just need to specify the full namespaces of the objects that are ambiguous. 您只需要指定模棱两可的对象的完整名称空间。 For example: 例如:

LocalNamespace.Something.Surveys localSurveys;
RemoteNamespace.Something.Surveys remoteSurveys;

You can also import the namespaces with an alias: 您还可以使用别名导入名称空间:

using Local = LocalNamespace.Something;
using Remote = RemoteNamespace.Something;

Local.Surveys localSurveys;
Remote.Surveys remoteSurveys;

It was not just that easy! 不仅如此简单! First I changed the Code Generation Strategy from T4 to Legacy ObjectContent. 首先,我将代码生成策略从T4更改为Legacy ObjectContent。 This can be done in the Entity Framework Model Diagram. 这可以在实体框架模型图中完成。 I did that in both ends of the service setup. 我在服务设置的两端都这样做了。 Remeber to delete the two .tt files nested under the .edmx. 请记住删除嵌套在.edmx下的两个.tt文件。 Then I set the Custom Tool Namespace for the .edmx (with the model window closed) to a different namespace. 然后,将.edmx(关闭模型窗口)的自定义工具命名空间设置为其他命名空间。

That worked it for me :-) 那对我有用:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM