Can Dapper be used to update and insert models?

.net c# dapper sql

Question

I've been playing with Dapper, trying to see if it's a good light-weight alternative to Entity Framework. So far I've been impressed with it's ability to quickly pull an entity <model> from a DB and get it into an IEnumerable of a model, or just create a single instance of a model. Very slick.

But what I'm not seeing is an easy way to update that model back to the db.

Example:

public class Dog
{
    public Guid Id { get; set; }
    public int? Age { get; set; }
    public string Name { get; set; }
    public float? Weight { get; set; }
} 

We can easily create an IEnumerable of Dog as follows:

IEnumerable<Dog> dogs = connection.Query<Dog>("SELECT * FROM Dog")

Or, for a single instance:

Dog dog = connection.Query<Dog>("SELECT * FROM Dog WHERE DogId = @dogid")

That all works great. But now, if we make changes to "dog" (say, just change it's weight), is there a slick, fast, easy way to get that entity back into the database without having to do a manual UPDATE query, listing out each field?

Thanks!

Accepted Answer

You can use the SqlMapperExtensions class from Dapper.Contrib.Extensions:

using Dapper;
using Dapper.Contrib.Extensions;

// don't forget the using since Update is an extension method

Dog entity; // you got it from somewhere
entity.Name = "fancy new dog name";
connection.Update(entity);

In order for this to work you need to add the [Key] annotation to your id. Should look something like this:

using System.ComponentModel.DataAnnotations;

public class Dog
{
    [Key]
    public long Id { get; set; }
    public int? Age { get; set; }
    public string Name { get; set; }
    public float? Weight { get; set; }
} 

Popular Answer

Dapper is a Micro - Orm having as a characteristics being simple and fast. The behavior you describe is more related to fully fledged ORM, that imply having some sort off session concept, mapping, and query generation ( with hopefully drivers for different SQL flavours ). This is definitely not the spirit of Dapper, that anyway make the process of updating/inserting easyer that plain ado.net, accepting POCO object as parameters for your query, ie:

.Execute("update mydogs  set age=@Age where id=@Id",dog);


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why