繁体   English   中英

将强类型对象转换为匿名对象

[英]Converting strongly typed object to anonymous one

我正在从事一个相对较大的项目,我们试图尽可能地暗示面向服务的体系结构,但是由于这个事实,我今天遇到了以下问题。 在我的表示层( ASP.NET Web Forms )中,我有一个User对象:

public class User
{
  public int ID {get; set;}
  public string Name {get; set;}
  public string Email {get; set;}
  Public string State {get; set;}
  public DateTime CreatedOn {get; set;}
  public string CreatedBy {get; set;}
}

原始项目中还有更多字段,但是对于这种情况,我认为这并不重要。 因此,在表示层中,我使用此对象在页面上显示用户信息,并让使用该应用程序的人员执行CRUD操作。 问题是当我想创建一个新用户时。 为此,有一个单独的Web Api 2服务项目-“ UserService, so all calls are made to the dedicated action from the UserService project and the response is the so all calls are made to the dedicated action from the project and the response is the新创建的用户project and the response is the ID”,并且它是创建该用户的初始状态。创建一个新用户,我做这样的事情:

    public User InsertUser(string username, string email, string createdBy)
    {
        var user = new
        {
            Username = username,
            Email = email,
            CreatedBy = createdBy
        }

        var result = //make call to the user service passing the anonymous object

        user newUser = new User
        {
            ID = result.ID,
            Username = username,
            Email = email,
            CreatedBy = createdBy,
            State = result.State
        }
        return newUser;
    }

由于某些原因,在不久的将来将无法解决,因此我无法引用某些DTO对象,并且该服务期望的是来自相同类型的对象或匿名对象,或者它无法反序列化数据。 这里有两件事确实让我感到困扰-第一件事情是我创建了一个实例的两次,理想情况下,该实例应该只是一个User类型的对象,在执行服务后,我可以向其中添加IDState像这样:

newUser.Id = result.Id
newUser.State = result.State

相反,我正在创建两个对象,这远非理想。 其次,我认为可能的一件事是从表示层创建User的实例,但是以某种方式转换它,以便服务操作能够反序列化它。 同样,这似乎是非常标准的情况,不包括我无法引用.dll或其他内容的事实。但是,也许,还有一个我不知道的解决方案?

编辑在Web Api部分上,方法是这样的:

public HttpResponseMessage InsertUser([FromBody]UserDTO userToInsert)
{
    var user = userToInsert;
    //Call Stored Procedure to Insert the user
    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, new {UserId = user.Id, State = user.State});
    return response;
}

在我为了使其工作而调用此方法的客户端中,我有一个嵌套类:

public class UserDetails
{
  public int UserId {get; set;}
  public string State {get; set;}
}

您是否看过序列化为JSON然后反序列化为匿名类型对象? 看看JSON.NET( http://www.newtonsoft.com/json/help/html/DeserializeAnonymousType.htm

暂无
暂无

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

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