2010-08-10 60 views
2

我正在使用連接到數據庫並利用實體框架的ASP.NET MVC(在C#中)站點。我希望人們能夠從站點修改數據庫中的信息(因爲在我看來,通過ASP.NET MVC站點顯示和驗證數據比桌面應用程序容易得多,同時更容易分發要做的工具)。然後,我希望用戶能夠將數據庫(在他們所做的更改之後)導出到可以由我創建的桌面應用程序加載的XML文件。我想知道是否有一種簡單的方法讓實體框架創建的類代表數據庫中的數據將其信息序列化爲XML文件?然後我假設我能夠在桌面應用程序中重複使用相同的生成代碼來讀取這些XML文件並創建對象以表示數據以供在該程序中使用?如何將實體從ASP.NET MVC網站序列化爲XML?

只是以某種方式導出數據庫,然後使用生成的相同代碼從客戶端計算機上的本地數據庫讀取而不是xml文件會更容易(客戶端計算機可能無法訪問Internet,因此數據必須存儲在本地)?

你會在不同的?預先感謝您的所有輸入!

回答

3

Xml-serializer是您所需要的。我用我發現和我的XML響應略微調整了這個XmlResult級需要:

public class XmlResult : ActionResult 
{ 
    private object objectToSerialize; 

    /// <summary> 
    /// Initializes a new instance of the <see cref="XmlResult"/> class. 
    /// </summary> 
    /// <param name="objectToSerialize">The object to serialize to XML.</param> 
    public XmlResult(object objectToSerialize) 
    { 
     this.objectToSerialize = objectToSerialize; 
    } 

    /// <summary> 
    /// Gets the object to be serialized to XML. 
    /// </summary> 
    public object ObjectToSerialize 
    { 
     get { return this.objectToSerialize; } 
    } 

    /// <summary> 
    /// Serialises the object that was passed into the constructor to XML and writes the corresponding XML to the result stream. 
    /// </summary> 
    /// <param name="context">The controller context for the current request.</param> 
    public override void ExecuteResult(ControllerContext context) 
    { 
     if (this.objectToSerialize != null) 
     { 
      context.HttpContext.Response.Clear(); 
      XmlRootAttribute root = new XmlRootAttribute("response"); 

      var xs = new System.Xml.Serialization.XmlSerializer(this.objectToSerialize.GetType(), root); 
      context.HttpContext.Response.ContentType = "text/xml"; 

      xs.Serialize(context.HttpContext.Response.Output, this.objectToSerialize); 
     } 
    } 

然後,每當你想從你的行動返回XML,你可以簡單地做:

public ActionResult GetStuffAsXml(int id) 
{ 
    var dbStuff = db.GetStuff(id); 
    // fetch stuff in database 
    return new XmlResult(dbStuff); 
} 

希望有幫助!

+0

這有幫助,謝謝!怎麼樣反向 - 從序列化XML到對象? – Evan 2010-08-10 17:17:32

+0

查看Xmlserializer上的Deserialize-method ..只要xml匹配對象,它就非常簡單直接... – 2010-08-10 19:44:56

1

嘗試這兩個環節,讓你開始 xml serializer WCF documentation

即使你必須添加時可能不使用WCF它可以簡化數據處理的WCF屬性。在我看來,通常最好將它傳遞到可信庫中,以防止陷入細節

+0

感謝您的鏈接! – Evan 2010-08-10 17:18:13