Can Dapper be used to update and insert models?

I played with Dapper trying to figure out if this is a good lightweight alternative to the Entity Framework. So far, I was impressed with the ability to quickly derive the <model> entity from the database and retrieve it in an IEnumerable model, or simply create one instance of the model. Very smooth.

But what I don't see is an easy way to upgrade this model to 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 IEnumerable from Dog as follows:

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

Or, for one instance:

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

Everything works great. But now, if we make changes to the “dog” (say, just change its weight), is there a spot, a quick and easy way to return this entity to the database without having to perform a manual UPDATE query, listing each field

Thanks!

+5
source share
2 answers

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

For this to work, you need to add the [Key] annotation to your id. It 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; } } 
+6
source

Dapper is a Micro-Orm that has simple and fast features. The behavior that you describe is more related to the full-blown ORM, which implies the presence of some sort of concept of a session, matching and generating queries (with reliable drivers for different SQL tastes). This is certainly not the spirit of Dapper, which in any case makes the update / paste process easier than a simple ado.net, taking a POCO object as parameters for your request, i.e.:

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

Source: https://habr.com/ru/post/1245702/


All Articles