Simple contract for use with FromSql()



With its recent improvements, I'm looking to move from Dapper back to EF (Core).

The majority of our code currently uses the standard patterns of mapping entities to tables, however we'd also like to be able to make simple ad-hoc queries that map to a simple POCO.

For example, say I have a SQL statement which returns a result set of strings. I created a class as follows...

public class SimpleStringDTO
    public string Result { get; set; }

.. and called it as such.

public DbSet<SimpleStringDTO> SingleStringResults { get; set; }

public IQueryable<SimpleStringDTO> Names()
    var sql = $"select name [result] from names";
    var result = this.SingleStringResults.FromSql(sql);
    return result;

My thoughts are that I could use the same DBSet and POCO for other simple queries to other tables.

When I execute it, EF throws an error "The entity type 'SimpleStringDTO' requires a primary key to be defined.".

Do I really need to define another field as a PK? There'll be cases where there isn't a PK defined. I just want something simple and flexible. Ideally, I'd rather not define a DBSet or POCO at all, just return the results straight to an IEnumerable<string>.

Can someone please point me towards best practises here?

4/9/2018 2:29:12 AM

Popular Answer

While I wait for EF Core 2.1 I've ended up adding a fake key to my model

public Guid Id { get; set; }

and then returning a fake Guid from SQL.

var sql = $"select newid(), name [result] from names";
4/9/2018 10:23:16 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow