Is there an equivalent to “NotMapped” for Dapper.Net and the Dapper.Net extensions?

StackOverflow https://stackoverflow.com/questions/12576225

  •  03-07-2021
  •  | 
  •  

Question

I've started to play with Dapper.Net, and am really loving it so far - however, I have run into one problem.

Say that I have a POCO class like:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName { get { return FirstName + " " + LastName; } }
}

Now, using Dapper.Net and the Dapper.Net extensions, I want to simply load all instances of that data type from the DB by doing this:

string connectionString = CloudConfigurationManager.GetSetting("DBConnection");
using (SqlConnection cn = new SqlConnection(connectionString))
{
    cn.Open();

    IEnumerable<Types.Person> entities = cn.GetList<Types.Person>();
    var forceMe = entities.ToList();
}

This works fine in the Linq setup, but when it hits the line with the .ToList(), which forces the evaluation, it blows up with "invalid column names" on FullName. Thinking that it might respect the Entity Framework DataAnnotations stuff for NotMapped, I tried adding a NotMapped attribute (after adding EF 5 to the project). This didn't work.

So, the question is, how do I tell Dapper.Net that a column isn't to be expected from the DB? Is this a problem with the extensions, trying to map a DB column for everything it sees in the model POCO? Do I need to revert to writing SQL, and explicitly ask for the columns that I want only, or is there a way to get an equivalent to NotMapped on the column?

Thanks in advance.

-adam

Was it helpful?

Solution

I think the only way to to ignore certain properties from being mapped is to implement an auto class mapper, where you can specify your custom field mappings. For example:

public class CustomMapper : ClassMapper<Foo>
{
    public CustomMapper()
    {
        Table("FooTable");
        Map(f => f.Id).Column("FooId").Key(KeyType.Identity);
        Map(f => f.DateOfBirth).Column("BirthDate");
        Map(f => f.FirstName).Column("First");
        Map(f => f.LastName).Column("Last");
        Map(f => f.FullName).Ignore();
        Map(f => f.Calculated).ReadOnly();
    }
}

public class Foo
{
    public int Id { get; set; }
    public DateTime DateOfBirth { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName
    {
        get { return string.Format("{0} {1}", FirstName, LastName); }
    }
}

In the above example, FullName is being ignored.

The auto-mapper also allows you to adjust table names, in case your POCO class names do not match table names.

Also, keep in mind that you must keep your custom maps in the same assembly as your POCO classes. The library uses reflection to find custom maps and it only scans one assembly.

Hope this helps, Good luck

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top