简体   繁体   中英

Entity Framework Code First with XML as Data Source

Is it possible to work with Entity Framework (Code First) and having the data source being an XML file? I need to populate the domain objects with values from the XML file.

The XML file has this structure:

<Person name="John" age="12">
    <Products>
        <Product id="1" name="Product 1" />
        <Product id="2" name="Product 2" />
        <Product id="3" name="Product 3" />
    </Products>
</Person>

C# domain objects has this structure:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public ICollection<Product> Products { get; set; }
}

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
}

I can use Linq to XML to parse trough each element of XML and populate the objects, but i was looking for a more automated way to do this (if exists).

You would need some XML database which is accessible through ADO.NET. Otherwise you are going to implement custom EF provider (which will be still based on ADO.NET) targeting your XML files. EF is for accessing databases.

If you want to have more "automated" way simply use XML serialization and related attributes - it will be same as using code first with data annotations.

Entity Framework code largely support data sources supported by ADO.net .

According to MSDN :

The ADO.NET Data Provider model provides a common managed interface in the .NET Framework for connecting to and interacting with a data store. The ADO.NET Entity Framework builds on top of the ADO.NET Data Provider model to allow for use of the Entity Framework with any data source for which a supported provider is available.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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