efcore icon indicating copy to clipboard operation
efcore copied to clipboard

Does EF7 support Xml columns ?

Open pserafin opened this issue 10 years ago • 8 comments

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.b__0(Object k) at System.Collections.Concurrent.ConcurrentDictionary2.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.b__0_4(IServiceProvider p) at Microsoft.Extensions.DependencyInjection.ServiceLookup.FactoryService.Invoke(ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass12_0.b__0(ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider) at Microsoft.EntityFrameworkCore.DbContext.get_Model() at Microsoft.EntityFrameworkCore.DbContext.SetTEntity at eHurt.Service.Common.DataLayer.Repositories.AgreementRepository.d__1.MoveNext()

I would be thankful for any help..

pserafin avatar Aug 10 '16 12:08 pserafin

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);
}

bricelam avatar Aug 10 '16 16:08 bricelam

ye I do that finally, but hoped 4 XElement

pserafin avatar Aug 10 '16 16:08 pserafin

Custom type mapping (issue #242) will enable that

bricelam avatar Aug 10 '16 17:08 bricelam

KK will wait 4 that. Thx

pserafin avatar Aug 12 '16 07:08 pserafin

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.

jzabroski avatar Oct 19 '18 21:10 jzabroski

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:

  1. As stated before, assume no direct XElement mapping support (not needed Xml Query support on server)
  2. Is there a way to make a hint or something on my Data property to say that it only needs DataString to properly function?

terryaney avatar Oct 19 '24 15:10 terryaney

@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 avatar Oct 19 '24 16:10 terryaney

@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.

roji avatar Oct 19 '24 19:10 roji