*Can You explain the Split on function in the multimap *
I am Trying to get the data from the Database using Dapper ORM. I have received the following error
System.ArgumentException : When using the multi-mapping APIs ensure you set the splitOn param if you have keys other than Id
Parameter name: splitOn
public abstract class Domain
{
public Guid Id { get; set; }
}
public abstract class ItemBase : Domain
{
private IList<Image> images = new List<Image>();
public Guid? ParentId { get; set; }
public string Name { get; set; }
public IList<Image> Images { get { return images; } }
}
public class Meal : ItemBase
{
}
public class Item : ItemBase
{
private IList<Meal> meals = new List<Meal>();
public IList<Meal> Meals { get { return meals; } };
}
public class Image : Domain
{
public byte Img { get; set; }
public string Description { get; set; }
}
public class MealImageLink : Domain
{
public Guid ItemId { get; set; }
public Guid ImageId { get; set; }
}
/* search function to take dat from the table */
private List<Meal> SearchMeals(Guid id)
{
var query = #"SELECT meal.[Name],meal.[Description],meal.
[Price],mealImage.[Image] as Img
FROM [MealItems] as meal
LEFT JOIN [MealImageLink] mealImageLink
on meal.Id= mealImageLink.MealItemId
LEFT JOIN [Images] mealImage on
mealImageLink.ImageId=mealImage.Id
WHERE meal.[ParentId]=#Id";
List<Meal> meals = ( _connection.Query<Meal, MealImageLink, Image, Meal>
(query, (meal, mealLink, mealImage) =>
{
meal.Images.Add(mealImage);
return meal;
}, new { #Id = id })).ToList();
return meals;
}
The multi-map feature is really more intended for scenarios like:
select foo.Id, foo.whatever, ...,
bar.Id, bar.something, ...,
blap.Id, blap.yada, ...
from foo ...
inner join bar ...
left outer join blap ...
or the lazier but not uncommon:
select foo.*, bar.*, blap.*
from ...
inner join bar ...
left outer join blap ...
But in both of these cases, there is a clear and obvious way to split the horizontal range into partitions; basically, whenever you see a column called Id, it is the next block. The name Id is configurable for convenience, and can be a delimited list of columns for scenarios where each table has a different primary key name (so User might have UserId, etc).
Your scenario seems quite different to this. It looks like you're currently only selecting 4 columns with no particular way of splitting them apart. I would suggest that in this case, it is easier to populate your model via a different API - in particular, the dynamic API:
var meals = new List<Meal>();
foreach(var row in _connection.Query(sql, new { #Id = id }))
{
string name = row.Name, description = row.Description;
decimal price = row.Price;
// etc
Meal meal = // TODO: build a new Meal object from those pieces
meals.Add(meal);
}
The dynamic API is accessed simply by not specifying any <...>. With that done, columns are accessed by name, with their types implied by what they are being assigned to - hence things like:
decimal price = row.Price;
Note: if you want to consume the row data "inline", then just cast as soon as possible, i.e.
// bad: forces everything to use dynamic for too long
new Meal(row.Name, row.Description, row.Price);
// good: types are nailed down immediately
new Meal((string)row.Name, (string)row.Description, (decimal)row.Price);
Does that help?
Tl;dr: I just don't think multi-mapping is relevant to your query.
Edit: here's my best guess at what you intend to do - it simply isn't a good fit for multi-map:
var meals = new List<Meal>();
foreach (var row in _connection.Query(query, new { #Id = id })) {
meals.Add(new Meal {
Name = (string)row.Name,
Images = {
new Image {
Description = (string)row.Description,
Img = (byte)row.Img
}
}
});
}
return meals;
Related
I have such sample data, which i should load to my db.
The schema is as follows. Courses and Modules are linked as one to many. Modules and Videos are linked as One to Many, Videos table contains foreign Key CourseId and the Course in the code below.
public class Video : EntityBase
{
[Key]
public int Id { get; set; }
[MaxLength(80), Required]
public string Title { get; set; }
public int ModuleId { get; set; }
public int CourseId { get; set; }
public Course Course { get; set; }
public Module Module { get; set; }
}
public static IEnumerable<Instructor> GetInstructors() => new List<Instructor>
{};
public static IEnumerable<Course> GetCourses(VODContext context)
{
var listOfInstructors = new List<int>
{
context.Instructors.First().Id,
context.Instructors.Skip(1).FirstOrDefault().Id,
context.Instructors.Skip(2).FirstOrDefault().Id
};
var courses = new List<Course>
{
new Course
{
InstructorId=listOfInstructors[0],
Title="Course 1. Foundations of C#",
Description= "master the power of the C ",
ImageUrl = "images/course2.jpg",
MarqueeImageUrl="/images/laptop.jpg",
Modules = new List<Module>
{
new Module
{
Title = "Module 1. Warm Up",
Videos = new List<Video>
{
new Video
{
Title="Video1",
Description="Setting up the enviroment",
Duration=10,
Thumbnail="/images/video1.jpg",
Url="https://www.youtube.com/watch?v=BJFyzpBcaCY"
},
new Video
{
Title="Video2",
Description="Complete Setting up the enviroment",
Duration=15,
Thumbnail="/images/video2.jpg",
Url="https://www.youtube.com/watch?v=stQ1IZEB2xk"
}
}
},
//2d Module
new Module
{
Title = "Module2. Fun begins.",
Videos= new List<Video>
{
new Video
{
Title ="Video3",
Duration = 20,
Thumbnail="/images/video3.jpg",
Url="https://www.youtube.com/watch?v=GZvSYJDk-us"
},
new Video
{
Title = "Video4. Learn the basics of http",
Duration = 30,
Thumbnail="/images/video4.jpg",
Url = "https://www.youtube.com/watch?v=XU5pw3QRYjQ"
}
}
}
}
}
}
}
The thing is that when _context.SaveChanges() is called there is an error Merge statement conflicted with Foreigh Key constraint FK_Video_Courses_CourseId.
As far as I understand EF can't add FK property to Video's CourseId value because it doesn't exist at the time of saving. I am not sure , though, shouldn't i expect from EF to fill in Id properties of child with the Id of parent, that is Video.CourseId= Course.Id.
I have two ideas of way outs, 1. Separate the data 2. Use hardcoded Ids but don't like both.
Is there a way to force EF to fill keys?
From Github:
Dapper allows you to map a single row to multiple objects. This is a
key feature if you want to avoid extraneous querying and eager load
associations.
Example:
Consider 2 classes: Post and User
> class Post {
> public int Id { get; set; }
> public string Title { get; set; }
> public string Content { get; set; }
> public User Owner { get; set; } }
>
> class User {
> public int Id { get; set; }
> public string Name { get; set; } }
Now let us say that we want to map a query that joins both the posts
and the users table. Until now
if we needed to combine the result of 2 queries, we'd need a new
object to express it but it makes more sense in this case to put the
User object inside the Post object.
When I do this (My classes are different names, but same construct), I get a Post and a User, a Post and a User. I'm using the Web API, so this is all JSON, if that matters. This is the way I'd see it if I did straight SQL in the Management Studio, you get the many rows and the corresponding User records
What if I want to send back the JSON that has the User once and all the posts in an array, then the next User, array of posts, etc.
id title content id name
1 Article1 Content1 55 Smith
2 Article2 Content2 55 Smith
3 Article3 Content3 55 Smith
I get the JSON back that has the User information over and over (as expected but not wanted). It's backwards.
What I want is a JSON object that has a format like this (I think this is correct):
{
"User": 55,
"Name": "Smith",
"Post": [
{
"id": 1,
"title": "title1",
"content":"MyContent1"
},
{
"id": 2,
"title": "title2",
"content":"MyContent2"
},
{
"id": 3,
"title": "title3",
"content":"MyContent2"
}
]
}
How do I do this? Right now I get the reverse. I thought I would simply change the classes around, but I did not because of the instructions on Github, the "makes more sense" part. I am using this,
(List<Post>)db.Query<Post, User, Paper>(sqlString, (post, user) => { post.user = user; return post; }, splitOn: "id");
I know I don't need the splitOn here, but in my real query the name is different than id.
This is pretty close:
https://www.tritac.com/developers-blog/dapper-net-by-example/
public class Shop {
public int? Id {get;set;}
public string Name {get;set;}
public string Url {get;set;}
public IList<Account> Accounts {get;set;}
}
public class Account {
public int? Id {get;set;}
public string Name {get;set;}
public string Address {get;set;}
public string Country {get;set;}
public int ShopId {get;set;}
}
var lookup = new Dictionary<int, Shop>()
conn.Query<Shop, Account, Shop>(#"
SELECT s.*, a.*
FROM Shop s
INNER JOIN Account a ON s.ShopId = a.ShopId
", (s, a) => {
Shop shop;
if (!lookup.TryGetValue(s.Id, out shop)) {
lookup.Add(s.Id, shop = s);
}
if (shop.Accounts == null)
shop.Accounts = new List<Account>();
shop.Accounts.Add(a);
return shop;
},
).AsQueryable();
var resultList = lookup.Values;
It makes the first object identifier. Not sure if I can use it like that or not. But this does do the array of books like I was asking, and I did not have to create a special object. Originally, it was supposed to be on Google Code, but I couldn't find this test on Github.
Since your SQL query is returning the flat records, i suggest you create a flat POCO and use dapper to map the result set to a collection of this. Once you have data in this collection, you can use LINQ GroupBy method to group it the way you want.
Assuming you have classes like
public class User
{
public int Id { set;get;}
public string Name { set;get;}
public IEnumerable<Post> Posts { set;get;}
}
public class Post
{
public int Id { set;get;}
public string Title{ set;get;}
public string Content { set;get;}
}
Now create the POCO for the flat result set row
public class UserPost
{
public int Id { set; get; }
public string Title { set; get; }
public string Content { set; get; }
public int UserId { set; get; }
public string Name { set; get; }
}
Now update your SQL query to return a result set with column name matching the above properties.
Now use Dapper to get the flat records
var userposts= new List<UserPost>();
using (var conn = new SqlConnection("YourConnectionString"))
{
userposts = conn.Query<UserPost>(query).ToList();
}
Now apply GroupBy
var groupedPosts = userposts.GroupBy(f => f.UserId, posts => posts, (k, v) =>
new User()
{
UserId = k,
Name = v.FirstOrDefault().Name,
Posts = v.Select(f => new Post() { Id = f.Id,
Title= f.Title,
Content = f.Content})
}).ToList();
Another option is to use .QueryMultiple
[Test]
public void TestQueryMultiple()
{
const string sql = #"select UserId = 55, Name = 'John Doe'
select PostId = 1, Content = 'hello'
union all select PostId = 2, Content = 'world'";
var multi = _sqlConnection.QueryMultiple(sql);
var user = multi.Read<User>().Single();
user.Posts = multi.Read<Post>().ToList();
Assert.That(user.Posts.Count, Is.EqualTo(2));
Assert.That(user.Posts.First().Content, Is.EqualTo("hello"));
Assert.That(user.Posts.Last().Content, Is.EqualTo("world"));
}
Update:
To return multiple users and their posts:
[Test]
public void TestQueryMultiple2()
{
const string sql = #"select UserId = 55, Name = 'John Doe'
select UserId = 55, PostId = 1, Content = 'hello'
union all select UserId = 55, PostId = 2, Content = 'world'";
var multi = _sqlConnection.QueryMultiple(sql);
var users = multi.Read<User>().ToList();
var posts = multi.Read<Post>().ToList();
foreach (var user in users)
{
user.Posts.AddRange(posts.Where(x => x.UserId == user.UserId));
}
Assert.That(users.Count, Is.EqualTo(1));
Assert.That(users.First().Posts.First().Content, Is.EqualTo("hello"));
Assert.That(users.First().Posts.Last().Content, Is.EqualTo("world"));
}
I am new to Dapper and trying to figure out how to query a Many-To-Many relationship.
I've looked around SO and Google but could not find an example.
I have a simple Many-To-Many scenario with 3 tables:
Albums table:
Artists table:
and the Many-To-Many table:
These are my POCOS:
public class Artist
{
public long Id { get; set; }
public string Name { get; set; }
}
public class Album
{
public long Id { get; set; }
public string Name { get; set; }
public List<Artist> Artists { get; set; }
}
Can someone provide the "correct" and efficient way to get a list of albums, and each album contains it's artists (the artists should have their Name property filled also) ?
I'm sure you must have found the solution by now. This could be helpful, may not be the neatest way to code it.
Is it possible to replicate Album and Artist classes?
If so, this is what i would do.
public List<Artist> GetAll()
{
using (SqlConnection conn = new SqlConnection(Conn.String))
{
conn.Open();
using (var multi = conn.QueryMultiple(StoredProcs.Artists.GetAll, commandType: CommandType.StoredProcedure))
{
var artists = multi.Read<Artist, AlbumArtist, Artist>((artist, albumArtist) =>
{
artist.albumArtist = albumArtist;
return artist;
}).ToList();
var albums = multi.Read<Album, AlbumArtist, Album>(
(album, albumArtist, album) =>
{
album.albumArtist = album;
return albums;
}).ToList();
conn.Close();
return artists;
}
}
}
Here's how the proc would look like
CREATE PROCEDURE [dbo].[YourProcName]
AS
BEGIN
SET NOCOUNT ON;
SELECT * from Artist a
left join AlbumArtist aa
on a.ArtistId = aa.ArtistId;
EXEC dbo.Album_GetAll
WITH RESULT SETS UNDEFINED;
END
Hope this helps.
I found a lot of explanations about this issue, but nothing that really helped me. The thing is simple. I have two tables on my dataModel: Events and TimeStamps, both have the field EntryID, which is the relation between them(the tables are in fact Views, I can't perform changes on DB, I can only query them).On my domainService, I have the created methods for getting data from each of the tables. So far, I am able to fill a dataGrid with data from only one of the tables, but what I really need is to display from both tables. In T-SQL it would be something like:
Select e.EntryID,t.closed_time
from Events e inner join TimeStamps t
on e.EntryID=t.EntryID
So I want to display on my dataGrid the Entry_ID and closed_time.I appreciate your help for solving my problem
I tried a new custom class
public class CustomTable
{
public string EntryId { get; set; }
public int closed_time { get; set; }
}
public IQueryable<CustomTable> GetJoined()
{
return (from i in this.ObjectContext.Events
join p in this.ObjectContext.TimeStamps p
on i.Entry_ID equals p.Entry_ID
select new CustomTable
{
EntryId = i.Entry_ID,
closed_Time = p.Closed_TIME
});
}
This is the additional code I added by myself, I'm pretty sure something is missing, this method and the class itself were added on my service.cs
This is the final code and procedures done, do not forget to build the project after each step:
1- Opened a new class under Myproject.Web(Add-->new item-->class)
namespace Myproject.Web
{
public class CustomTable
{
[Key]
public string EntryId { get; set; }
public int closed_Time { get; set; }
}
}
2-Added on IncidentService.cs:
public IQueryable<CustomTable> GetJoined()
{
return (from i in this.ObjectContext.Events
join p in this.ObjectContext.TimeStamps p
on i.Entry_ID equals p.Entry_ID
select new CustomTable
{
EntryId = i.Entry_ID,
closed_Time = p.Closed_TIME
});
}
3-Added on Mypage.xaml.cs
public MyPage()
{
InitializeComponent();
this.dataGrid1.ItemsSource = _IncidentContext.CustomTables;
_IncidentContext.Load(_IncidentContext.GetJoinedQuery());
DataGridTextColumn entry = new DataGridTextColumn();
entry.Binding = new System.Windows.Data.Binding("EntryId");
entry.Header = "Entry Id";
DataGridTextColumn closed = new DataGridTextColumn();
closed.Binding = new System.Windows.Data.Binding("closed_Time");
closed.Header = "Closed Time";
dataGrid1.Columns.Add(entry);
dataGrid1.Columns.Add(closed);
}
I hope this will help others with same issue, I spent 3 days working on this solution!!
I am new to the Dapper micro ORM. So far I am able to use it for simple ORM related stuff but I am not able to map the database column names with the class properties.
For example, I have the following database table:
Table Name: Person
person_id int
first_name varchar(50)
last_name varchar(50)
and I have a class called Person:
public class Person
{
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Please note that my column names in the table are different from the property name of the class to which I am trying to map the data which I got from the query result.
var sql = #"select top 1 PersonId,FirstName,LastName from Person";
using (var conn = ConnectionFactory.GetConnection())
{
var person = conn.Query<Person>(sql).ToList();
return person;
}
The above code won't work as the column names don't match the object's (Person) properties. In this scenario, is there anything i can do in Dapper to manually map (e.g person_id => PersonId) the column names with object properties?
Dapper now supports custom column to property mappers. It does so through the ITypeMap interface. A CustomPropertyTypeMap class is provided by Dapper that can do most of this work. For example:
Dapper.SqlMapper.SetTypeMap(
typeof(TModel),
new CustomPropertyTypeMap(
typeof(TModel),
(type, columnName) =>
type.GetProperties().FirstOrDefault(prop =>
prop.GetCustomAttributes(false)
.OfType<ColumnAttribute>()
.Any(attr => attr.Name == columnName))));
And the model:
public class TModel {
[Column(Name="my_property")]
public int MyProperty { get; set; }
}
It's important to note that the implementation of CustomPropertyTypeMap requires that the attribute exist and match one of the column names or the property won't be mapped. The DefaultTypeMap class provides the standard functionality and can be leveraged to change this behavior:
public class FallbackTypeMapper : SqlMapper.ITypeMap
{
private readonly IEnumerable<SqlMapper.ITypeMap> _mappers;
public FallbackTypeMapper(IEnumerable<SqlMapper.ITypeMap> mappers)
{
_mappers = mappers;
}
public SqlMapper.IMemberMap GetMember(string columnName)
{
foreach (var mapper in _mappers)
{
try
{
var result = mapper.GetMember(columnName);
if (result != null)
{
return result;
}
}
catch (NotImplementedException nix)
{
// the CustomPropertyTypeMap only supports a no-args
// constructor and throws a not implemented exception.
// to work around that, catch and ignore.
}
}
return null;
}
// implement other interface methods similarly
// required sometime after version 1.13 of dapper
public ConstructorInfo FindExplicitConstructor()
{
return _mappers
.Select(mapper => mapper.FindExplicitConstructor())
.FirstOrDefault(result => result != null);
}
}
And with that in place, it becomes easy to create a custom type mapper that will automatically use the attributes if they're present but will otherwise fall back to standard behavior:
public class ColumnAttributeTypeMapper<T> : FallbackTypeMapper
{
public ColumnAttributeTypeMapper()
: base(new SqlMapper.ITypeMap[]
{
new CustomPropertyTypeMap(
typeof(T),
(type, columnName) =>
type.GetProperties().FirstOrDefault(prop =>
prop.GetCustomAttributes(false)
.OfType<ColumnAttribute>()
.Any(attr => attr.Name == columnName)
)
),
new DefaultTypeMap(typeof(T))
})
{
}
}
That means we can now easily support types that require map using attributes:
Dapper.SqlMapper.SetTypeMap(
typeof(MyModel),
new ColumnAttributeTypeMapper<MyModel>());
Here's a Gist to the full source code.
This works fine:
var sql = #"select top 1 person_id PersonId, first_name FirstName, last_name LastName from Person";
using (var conn = ConnectionFactory.GetConnection())
{
var person = conn.Query<Person>(sql).ToList();
return person;
}
Dapper has no facility that allows you to specify a Column Attribute, I am not against adding support for it, providing we do not pull in the dependency.
For some time, the following should work:
Dapper.DefaultTypeMap.MatchNamesWithUnderscores = true;
I do the following using dynamic and LINQ:
var sql = #"select top 1 person_id, first_name, last_name from Person";
using (var conn = ConnectionFactory.GetConnection())
{
List<Person> person = conn.Query<dynamic>(sql)
.Select(item => new Person()
{
PersonId = item.person_id,
FirstName = item.first_name,
LastName = item.last_name
}
.ToList();
return person;
}
Here is a simple solution that doesn't require attributes allowing you to keep infrastructure code out of your POCOs.
This is a class to deal with the mappings. A dictionary would work if you mapped all the columns, but this class allows you to specify just the differences. In addition, it includes reverse maps so you can get the field from the column and the column from the field, which can be useful when doing things such as generating sql statements.
public class ColumnMap
{
private readonly Dictionary<string, string> forward = new Dictionary<string, string>();
private readonly Dictionary<string, string> reverse = new Dictionary<string, string>();
public void Add(string t1, string t2)
{
forward.Add(t1, t2);
reverse.Add(t2, t1);
}
public string this[string index]
{
get
{
// Check for a custom column map.
if (forward.ContainsKey(index))
return forward[index];
if (reverse.ContainsKey(index))
return reverse[index];
// If no custom mapping exists, return the value passed in.
return index;
}
}
}
Setup the ColumnMap object and tell Dapper to use the mapping.
var columnMap = new ColumnMap();
columnMap.Add("Field1", "Column1");
columnMap.Add("Field2", "Column2");
columnMap.Add("Field3", "Column3");
SqlMapper.SetTypeMap(typeof (MyClass), new CustomPropertyTypeMap(typeof (MyClass), (type, columnName) => type.GetProperty(columnMap[columnName])));
An easy way to achieve this is to just use aliases on the columns in your query.
If your database column is PERSON_ID and your object's property is ID, you can just do
select PERSON_ID as Id ...
in your query and Dapper will pick it up as expected.
Taken from the Dapper Tests which is currently on Dapper 1.42.
// custom mapping
var map = new CustomPropertyTypeMap(typeof(TypeWithMapping),
(type, columnName) => type.GetProperties().FirstOrDefault(prop => GetDescriptionFromAttribute(prop) == columnName));
Dapper.SqlMapper.SetTypeMap(typeof(TypeWithMapping), map);
Helper class to get name off the Description attribute (I personally have used Column like #kalebs example)
static string GetDescriptionFromAttribute(MemberInfo member)
{
if (member == null) return null;
var attrib = (DescriptionAttribute)Attribute.GetCustomAttribute(member, typeof(DescriptionAttribute), false);
return attrib == null ? null : attrib.Description;
}
Class
public class TypeWithMapping
{
[Description("B")]
public string A { get; set; }
[Description("A")]
public string B { get; set; }
}
Before you open the connection to your database, execute this piece of code for each of your poco classes:
// Section
SqlMapper.SetTypeMap(typeof(Section), new CustomPropertyTypeMap(
typeof(Section), (type, columnName) => type.GetProperties().FirstOrDefault(prop =>
prop.GetCustomAttributes(false).OfType<ColumnAttribute>().Any(attr => attr.Name == columnName))));
Then add the data annotations to your poco classes like this:
public class Section
{
[Column("db_column_name1")] // Side note: if you create aliases, then they would match this.
public int Id { get; set; }
[Column("db_column_name2")]
public string Title { get; set; }
}
After that, you are all set. Just make a query call, something like:
using (var sqlConnection = new SqlConnection("your_connection_string"))
{
var sqlStatement = "SELECT " +
"db_column_name1, " +
"db_column_name2 " +
"FROM your_table";
return sqlConnection.Query<Section>(sqlStatement).AsList();
}
Messing with mapping is borderline moving into real ORM land. Instead of fighting with it and keeping Dapper in its true simple (fast) form, just modify your SQL slightly like so:
var sql = #"select top 1 person_id as PersonId,FirstName,LastName from Person";
If you're using .NET 4.5.1 or higher checkout Dapper.FluentColumnMapping for mapping the LINQ style. It lets you fully separate the db mapping from your model (no need for annotations)
This is piggy backing off of other answers. It's just a thought I had for managing the query strings.
Person.cs
public class Person
{
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public static string Select()
{
return $"select top 1 person_id {nameof(PersonId)}, first_name {nameof(FirstName)}, last_name {nameof(LastName)}from Person";
}
}
API Method
using (var conn = ConnectionFactory.GetConnection())
{
var person = conn.Query<Person>(Person.Select()).ToList();
return person;
}
The simple solution to the problem Kaleb is trying to solve is just to accept the property name if the column attribute doesn't exist:
Dapper.SqlMapper.SetTypeMap(
typeof(T),
new Dapper.CustomPropertyTypeMap(
typeof(T),
(type, columnName) =>
type.GetProperties().FirstOrDefault(prop =>
prop.GetCustomAttributes(false)
.OfType<ColumnAttribute>()
.Any(attr => attr.Name == columnName) || prop.Name == columnName)));
The easier way (same as #Matt M's answer but corrected and added fallback to default map)
// override TypeMapProvider to return custom map for every requested type
Dapper.SqlMapper.TypeMapProvider = type =>
{
// create fallback default type map
var fallback = new DefaultTypeMap(type);
return new CustomPropertyTypeMap(type, (t, column) =>
{
var property = t.GetProperties().FirstOrDefault(prop =>
prop.GetCustomAttributes(typeof(ColumnAttribute))
.Cast<ColumnAttribute>()
.Any(attr => attr.Name == column));
// if no property matched - fall back to default type map
if (property == null)
{
property = fallback.GetMember(column)?.Property;
}
return property;
});
};
for all of you who use Dapper 1.12, Here's what you need to do to get this done:
Add a new column attribute class:
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property]
public class ColumnAttribute : Attribute
{
public string Name { get; set; }
public ColumnAttribute(string name)
{
this.Name = name;
}
}
Search for this line:
map = new DefaultTypeMap(type);
and comment it out.
Write this instead:
map = new CustomPropertyTypeMap(type, (t, columnName) =>
{
PropertyInfo pi = t.GetProperties().FirstOrDefault(prop =>
prop.GetCustomAttributes(false)
.OfType<ColumnAttribute>()
.Any(attr => attr.Name == columnName));
return pi != null ? pi : t.GetProperties().FirstOrDefault(prop => prop.Name == columnName);
});
I know this is a relatively old thread, but I thought I'd throw what I did out there.
I wanted attribute-mapping to work globally. Either you match the property name (aka default) or you match a column attribute on the class property. I also didn't want to have to set this up for every single class I was mapping to. As such, I created a DapperStart class that I invoke on app start:
public static class DapperStart
{
public static void Bootstrap()
{
Dapper.SqlMapper.TypeMapProvider = type =>
{
return new CustomPropertyTypeMap(typeof(CreateChatRequestResponse),
(t, columnName) => t.GetProperties().FirstOrDefault(prop =>
{
return prop.Name == columnName || prop.GetCustomAttributes(false).OfType<ColumnAttribute>()
.Any(attr => attr.Name == columnName);
}
));
};
}
}
Pretty simple. Not sure what issues I'll run into yet as I just wrote this, but it works.
Kaleb Pederson's solution worked for me. I updated the ColumnAttributeTypeMapper to allow a custom attribute (had requirement for two different mappings on same domain object) and updated properties to allow private setters in cases where a field needed to be derived and the types differed.
public class ColumnAttributeTypeMapper<T,A> : FallbackTypeMapper where A : ColumnAttribute
{
public ColumnAttributeTypeMapper()
: base(new SqlMapper.ITypeMap[]
{
new CustomPropertyTypeMap(
typeof(T),
(type, columnName) =>
type.GetProperties( BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance).FirstOrDefault(prop =>
prop.GetCustomAttributes(true)
.OfType<A>()
.Any(attr => attr.Name == columnName)
)
),
new DefaultTypeMap(typeof(T))
})
{
//
}
}