1

Is it possible to return extra dynamic columns in Entity Framework with the FromSqlRaw?

The basic concept would be something like this

var contacts = DbContext.Contacts.FromSqlRaw("Select *, 'Some Dyn Field' as Field1 From Contacts ");

How could I get access to Field1? I have a much more complex process I am trying to solve but this is a general concept.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jonathan
  • 1,725
  • 3
  • 19
  • 45
  • 1
    Not directly, though this will probably be along the lines of what you want to do: https://stackoverflow.com/questions/26749429/anonymous-type-result-from-sql-query-execution-entity-framework Your example won't work because to return "Contacts", that "Some Dynamic Field" would have to be recognized as part of a Contact entity. – Steve Py Nov 09 '20 at 02:09

1 Answers1

0

The fields of query DbContext.Contacts.FromSqlRaw("Select *, 'Some Dyn Field' as Field1 From Contacts ") should contain the same fields as Contact class of DbContext of your EF otherwise you will have a runtime error. If you wont to have some extra fields you to create a new class - MyExtraField class and add this class to context of EF

public virtual DbSet<MyExtraField> MyExtraFields { get; set; }

.............

  modelBuilder.Entity<MyExtraField>(e =>
            {
                e.HasNoKey();
            });
.....

If it doesn't fit your requirements you can try to use the good old ADO.NET.

Serge
  • 40,935
  • 4
  • 18
  • 45