williambryan777 / dapper-dot-net

Automatically exported from code.google.com/p/dapper-dot-net
Other
0 stars 0 forks source link

Implicit casting #44

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
Hi guys,

This may be on the same lines as issue 24.

I've got a class that supports implicit casting to/from string.

When dapper tries to do the cast, it falls over. I did try create a custom type 
converter, but it doesn't look like this is being used.

Is there anyway I can tell dapper how to convert from string to MyType?

Original issue reported on code.google.com by b...@planetcloud.co.uk on 14 Jul 2011 at 8:03

GoogleCodeExporter commented 9 years ago
Can you please illustrate with a short (but complete) failing test scenario, so 
that we  can clearly see the issue?

To clarify - at the moment *no* additional conversions are performed silently, 
except for strings<===>enums.

Original comment by marc.gravell on 14 Jul 2011 at 8:06

GoogleCodeExporter commented 9 years ago
Hi Marc,

I think the initial issue was that I had no public constructor, thus causing it 
to throw. Adding one is far from ideal, but I did so just to see if it would 
actually cast implicitly (which it still does not). Here's the test.

        public class Slug
        {
            private string value;

            public Slug() { }

            public Slug(string value) {
                this.value = value;
            }

            public static implicit operator Slug(string value)            {
                return new Slug((value ?? string.Empty).Trim());
            }

            public static implicit operator string(Slug name) {
                return name.ToString();
            }

            public override string ToString()
            {
                return value;
            }
        }

        [TestFixture]
        public class DapperImplicitTests
        {
            [Test]
            public void Should_cast_implicitly()
            {
                var connection = new SqlConnection("data source=(local)\\sqlexpress;trusted_connection=yes");
                connection.Open();

                var sql = "select 'test-slug' as Slug";

                var slug = connection.Query<Slug>(sql).Single();
                slug.ShouldEqual("test-slug");
            }
        }

Original comment by b...@planetcloud.co.uk on 14 Jul 2011 at 8:30

GoogleCodeExporter commented 9 years ago
Hi, you can do it like that:

(choose which apply)
SqlMapper.AddTypeMap(typeof(Slug), DbType.String);
SqlMapper.AddTypeMap(typeof(Slug), DbType.StringFixedLength);
SqlMapper.AddTypeMap(typeof(Slug), DbType.AnsiString);
SqlMapper.AddTypeMap(typeof(Slug), DbType.AnsiStringFixedLength);

You can add this mapping into the initialization code of you application OR add 
it into the static constructor of your Slug to keep it together.

Original comment by masta2ooo on 16 Jun 2014 at 4:21