From 67eaaa16c0e8fa61024bcc074c6bb0f288009429 Mon Sep 17 00:00:00 2001 From: Bret Copeland Date: Mon, 6 Feb 2017 16:04:33 -0500 Subject: [PATCH] Add GetRowParser documentation/example --- Readme.md | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/Readme.md b/Readme.md index 7fc59b8..c74f4fc 100644 --- a/Readme.md +++ b/Readme.md @@ -374,6 +374,50 @@ Query("select * from Thing where Name = @Name", new {Name = new DbString On SQL Server it is crucial to use the unicode when querying unicode and ansi when querying non unicode. +Type Switching Per Row +--------------------- + +Usually you'll want to treat all rows from a given table as the same data type. However, there are some circumstances where it's useful to be able to parse different rows as different data types. This is where `IDataReader.GetRowParser` comes in handy. + +Imagine you have a database table named "Shapes" with the columns: `Id`, `Type`, and `Data`, and you want to parse its rows into `Circle`, `Square`, or `Triangle` objects based on the value of the Type column. + +```csharp +var shapes = new List(); +using (var reader = connection.ExecuteReader("select * from Shapes")) +{ + // Generate a row parser for each type you expect. + // The generic type is what the parser will return. + // The argument (typeof(*)) is the concrete type to parse. + var circleParser = reader.GetRowParser(typeof(Circle)); + var squareParser = reader.GetRowParser(typeof(Square)); + var triangleParser = reader.GetRowParser(typeof(Triangle)); + + var typeColumnIndex = reader.GetOrdinal("Type"); + + while (reader.Read()) + { + IShape shape; + var type = (ShapeType)reader.GetInt32(typeColumnIndex); + switch (type) + { + case ShapeType.Circle: + shape = circleParser(reader); + break; + case ShapeType.Square: + shape = squareParser(reader); + break; + case ShapeType.Triangle: + shape = triangleParser(reader); + break; + default: + throw new NotImplementedException(); + } + + shapes.Add(shape); + } +} +``` + Limitations and caveats --------------------- Dapper caches information about every query it runs, this allow it to materialize objects quickly and process parameters quickly. The current implementation caches this information in a ConcurrentDictionary object. The objects it stores are never flushed. If you are generating SQL strings on the fly without using parameters it is possible you will hit memory issues. We may convert the dictionaries to an LRU Cache. -- GitLab