簡體   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