Does EF7 support Xml columns ?
Hi, Im trying to retrive dataset from stored procedure using EF7. One of resultset columns is xml type
Steps to reproduce
example resultset from sProcedure
[DocNo] [Products]
1 <Root><P><MasterNo>X-01</MasterNo><Name>test_1</Name></P></Root>
2 <Root><P><MasterNo>X-01</MasterNo><Name>test_1</Name></P><P><MasterNo>X-02</MasterNo><Name>test_2</Name></P></Root>
Destination entity is:
public class Test
{
public string DocNo { get; set; }
public System.Xml.Linq.XElement Products { get; set; }
}
Context CommonDbContext:
{...}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Test>().HasKey(x => x.DocNo);
}
public virtual DbSet<Test> Test{ get; set; }
DAL method:
public async Task<IList<Test>> DoSth()
{
using (var db = new CommonDbContext())
{
string command = @"exec [dbo].[GetCustomerAgreements] 'xxxxx'";
return await db.Set<Test>().FromSql(command).ToListAsync();
}
}
The issue
When comes to retrive data and map it do DbSet i get an error:
inner ex.:
"The key {'TempId'} contains properties in shadow state and is referenced by a relationship from 'XElement' to 'Test.Products'. Configure a non-shadow principal key for this relationship."
st. trace:
at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.KeyConvention.Apply(InternalModelBuilder modelBuilder)
at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.OnModelBuilt(InternalModelBuilder modelBuilder)
at Microsoft.EntityFrameworkCore.Metadata.Internal.Model.Validate()
at Microsoft.EntityFrameworkCore.Metadata.Internal.InternalModelBuilder.Validate()
at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)
at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.<>c__DisplayClass14_0.2.GetOrAdd(TKey key, Func2 valueFactory)
at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)
at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel()
at Microsoft.EntityFrameworkCore.Internal.LazyRef`1.get_Value()
at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()
at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServiceCollectionExtensions.<>c.
I would be thankful for any help..
You can map to xml columns using string properties. This gives you limited read/write support, but not the rich LINQ support you might expect.
class Test
{
public string DocNo { get; set; }
public string Products { get; set; }
// Unmapped property that converts the string to an XElement
public XElement ProductsXml
=> XElement.Parse(Products);
}
ye I do that finally, but hoped 4 XElement
Custom type mapping (issue #242) will enable that
KK will wait 4 that. Thx
Is there example code on how #242 addresses xml? Given XML has completely custom query language and deeply nested structed data (object graphs), it seems a bit of a large lift.
Hi @ajcvickers , I'm assuming the suggested support for Xml columns is to create unmapped properties? If so, I have a question...my entity is defined as:
[Column("ahqData", TypeName = "xml")]
public string DataString { get; set; } = null!;
[NotMapped]
public System.Xml.Linq.XElement Data
{
get { return System.Xml.Linq.XElement.Parse(DataString); }
set { DataString = value.ToString(); }
}
If I run a query as follows where I access the 'unmapped' property:
context.AdHocQueries.Select(a => new { a.Key, a.Data } ).Take( 10 ).Dump();
The generated SQL is as follows where it selects the 'entire' table row data:
Executed DbCommand (60ms) [Parameters=[@__p_0='10'], CommandType='Text', CommandTimeout='30']
SELECT TOP(@__p_0) [a].[ahqKey], [a].[ahqComment], [a].[ahqCreatedBy], [a].[ahqData], [a].[ahqDateCreated], [a].[ahqDateExpires], [a].[ahqDateUpdated], [a].[ahqEditLock], [a].[ahqgKey], [a].[ahqIsPublic], [a].[ahqLastRowCount], [a].[ahqName], [a].[ahqUpdatedBy]
FROM [AdHocQuery] AS [a]
If I run the query where I access only the mapped property:
context.AdHocQueries.Select(a => new { a.Key, a.DataString } ).Take( 10 ).Dump();
The generated SQL is as follows where it selects only the required columns:
Executed DbCommand (59ms) [Parameters=[@__p_0='10'], CommandType='Text', CommandTimeout='30']
SELECT TOP(@__p_0) [a].[ahqKey] AS [Key], [a].[ahqData] AS [DataString]
FROM [AdHocQuery] AS [a]
My questions:
- As stated before, assume no direct
XElementmapping support (not needed Xml Query support on server) - Is there a way to make a hint or something on my
Dataproperty to say that it only needsDataStringto properly function?
@ajcvickers Actually found this and went this route and it only selects column needed. Assume this is recommended way, and there isn't a built in way?
modelBuilder.Entity<AdHocQuery>( entity =>
{
entity.Property( e => e.Data )
.HasConversion(
xml => xml.ToString(),
s => XElement.Parse( s ) );
} );
@terryaney you can map XML columns as .NET strings out-of-the-box, since this is what the SQL Server driver (SqlClient) supports natively. If you'd like to work with XElement instead, you can indeed use a value converter as you've done above.