Entity Framework 6 Partial Stored Procedure Mapping - c#

For example, I have a class like this:
public class Employee
{
public int Id;
public string Name;
public double Salary;
public DateTime BoD;
}
and a stored procedure that returns only the id and salary columns for employee, what I want using Entity Framework (6 or 5), is the below:
execute the stored procedure, and map its results to an Employee object, without using complex types.
please help me.
Note:
please consider that the procedure will be more complicated, and I don't want to use linq and returns name or Bod.
this is so important in my project.
in nhibernate you can do that.

Here is what you need :
// Create Two Classes
public class Employee
{
public int Id;
public string Name;
public double Salary;
public DateTime BoD;
}
public class EmployeeIDAndSalary
{
public int Id;
public double Salary;
}
// Create Extension Function
// We need to use Automapper extension library.
// Install Automapper using Nuget Package Manager. And create a class and add this code in it.
namespace Models.Mapper
{
public static class EmployeeMapper
{
public static Employee MapToEmployee(this EmployeeIDAndSalary obj)
{
if (obj != null)
{
Employee model = AutoMapper.TryAutoMap<Employee>(obj);
return model ;
}
return new Employee();
}
public static IEnumerable<Employee> MapToEmployee(this IEnumerable<EmployeeIDAndSalary> obj)
{
if (obj != null)
{
return obj.Select(x => x.ConvertToEmployee()).AsEnumerable();
}
return new List<Models.Employee>();
}
}
public static class AutoMapper
{
static AutoMapper()
{
}
public static T TryAutoMap<T>(object fromObject)
{
try
{
var currentObj = Activator.CreateInstance<T>();
var type = currentObj.GetType();
var propInfo = type.GetProperties();
var _type = fromObject.GetType();
foreach (var item in _type.GetProperties())
{
var prop = propInfo.Where(c => c.Name == item.Name).FirstOrDefault();
if (prop != null)
{
// if (prop.GetType().IsAssignableFrom(item.GetType()))
{
if (IsGenericEnumerable(item.PropertyType))
{
continue;
}
if (prop.GetType() == item.GetType())
{
try
{
prop.SetValue(currentObj, item.GetValue(fromObject, null), null);
}
catch { }
}
}
}
}
return currentObj;
}
catch
{
return default(T);
}
}
private static bool IsClass(Type type)
{
return type.IsClass && !type.IsPrimitive;
}
private static bool IsGenericEnumerable(Type type)
{
if (type.FullName.ToLower().Contains("datamodel") || type.FullName.ToLower().Contains("models") || type.FullName.ToLower().Contains("collection"))
{
return true;
}
return false;
}
}
}
// Use Namespace -> Models.Mapper.EmployeeMapper;
// Execute your procedure using EmployeeIdAndSalary
try
{
var _objList = context.SqlQuery<EmployeeIDAndSalary>("YourProcedureName #SpParameterName", param).ToList().MapToEmployee();
}
catch
{ }
// I think this is all what you need.

Related

Hash set - unique items not added

I have a class that contains the following:
HashSet<CookieSetItem> _set = new HashSet<CookieSetItem>();
public IEnumerable<CookieSetItem> Set
{
get { return _set; }
}
public void Add(int id)
{
id.ThrowDefault("id");
var item = new CookieSetItem(id);
if (_set.Add(item))
{
// this only happens for the first call
base.Add();
}
}
When I call the add method multiple times, say with ID's 1,2,3 etc, only the first item is added.
Obviously I'm confused as a new CookieSetItem is being created each time with a unique element (the ID), so why is it not being added?.
For completeness, here's the cookie set class:
public sealed class CookieSetItem
{
readonly DateTime _added;
readonly int _id;
public DateTime Added
{
get { return _added; }
}
public int ID
{
get { return _id; }
}
public CookieSetItem(int id)
: this(id, DateTime.Now)
{
}
public CookieSetItem(int id, DateTime added)
{
id.ThrowDefault("id");
added.ThrowDefault("added");
_id = id;
_added = added;
}
}
Got to the bottom of it - more than one error, which clouded the overall view.
Firstly I updated my class with IEquatable, which fixed the adding problem. Secondly, I found that the end result which was to update a cookie with a string version of the hashset also failed due to the fact that it was not encrypted. Here's the amended class that fixed the original problem.
public sealed class DatedSet : IEquatable<DatedSet>
{
readonly DateTime _added;
readonly int _id;
public DateTime Added
{
get { return _added; }
}
public int ID
{
get { return _id; }
}
public DatedSet(int id)
: this(id, DateTime.Now)
{
}
public DatedSet(int id, DateTime added)
{
id.ThrowDefault("id");
added.ThrowDefault("added");
_id = id;
_added = added;
}
public bool Equals(DatedSet other)
{
if (other == null) return false;
return this.ID == other.ID;
}
public override bool Equals(Object obj)
{
if (obj == null) return false;
var ds = obj as DatedSet;
return ds == null ? false : Equals(ds);
}
public override int GetHashCode()
{
return ID.GetHashCode();
}
}
Thanks for the advice.

Get custom attribute from specific object property/field

I've been searching for a while now and tested several methods, but i didn't find the answer i was looking for. I'll try to explain.
I have an object with several fields/properties. These properties have custom attributes.
What i want is to get the custom attribute from a specific propertie without all the knowlege of the object.
The are the base classes
// FieldAttr has a public Text propery
public class TestObject
{
// Declare fields
[FieldAttr("prop_testfld1")]
public FLDtype1 testfld1 = new FLDtype1();
[FieldAttr("prop_testfld2")]
public FLDtype2 testfld2 = new FLDtype2();
[FieldAttr("prop_testfld3")]
public FLDtype1 testfld3;
}
public class FLDtype1
{
public string Value { get; set; }
}
public class FLDtype2
{
public Guid Value { get; set; }
}
public sealed class FieldAttr: System.Attribute
{
private string _txt;
public EntityFieldType(string txt)
{
this._text = txt;
}
public string Text { get { return this._text; } }
}
And i want to be able to do this in my application:
static void Main(string[] args)
{
TestObject test = new TestObject();
// (Option 1: preferred)
Console.WriteLine(test.testfld1.getFieldAttr().Text);
// (Option 2)
Console.WriteLine(test.getFieldAttr(test.testfld1).Text);
}
Is this possible? I've seen methods to get custom attribute values from all properties/fields of an object, but not for a specific field.
I've got a working method to get custom attribute from an enum, but wasn't able to recreate it for object fields/properties. This is because i couldn't get the name of the field i was trying to explore, because (for example) test.testfld1.ToString() give's me "ns.FLDtype1".
Looking forward for the answer :)
(and excuse my english)
Yes it is possible:
public static class Extensions
{
public static FieldAttr GetFieldAttr(
this TestObject source,
Expression<Func<TestObject,object>> field)
{
var member = field.Body as MemberExpression;
if (member == null) return null; // or throw exception
var fieldName = member.Member.Name;
var test = typeof (TestObject);
var fieldType = test.GetField(fieldName);
if (fieldType != null)
{
var attribute = fieldType.GetCustomAttribute<FieldAttr>();
return attribute;
}
return null;
}
}
Usage:
TestObject test = new TestObject();
var attr = test.GetFieldAttr(x => x.testfld3);
if(attr != null) Console.WriteLine(attr.Text);
Here is the fiddle
After another day of trial and error I decided to make use of Selman22 answer with a little modification. This is code I created:
public class TestObject : iTestObject
{
// Declare fields
[FieldAttr("prop_testfld1")]
public FLDtype1 testfld1 = new FLDtype1();
[FieldAttr("prop_testfld2")]
public FLDtype2 testfld2 = new FLDtype2();
[FieldAttr("prop_testfld3")]
public FLDtype1 testfld3;
}
public class FLDtype1 : iField
{
public string Value { get; set; }
}
public class FLDtype2 : iField
{
public Guid Value { get; set; }
}
public sealed class FieldAttr: System.Attribute
{
private string _txt;
public FieldAttr(string txt)
{
this._txt = txt;
}
public string Text { get { return this._txt; } }
}
public interface iField { }
public interface iTestObject { }
public static class Extensions
{
public static FieldAttr GetFieldAttr<T>(this T source, Expression<Func<iField>> field) where T : iTestObject
{
// Get member body. If no body present, return null
MemberExpression member = (MemberExpression)field.Body;
if (member == null) { return null; }
// Get field info. If no field info present, return null
FieldInfo fieldType = typeof(T).GetField(member.Member.Name);
if (fieldType == null) { return null; }
// Return custom attribute
return fieldType.GetCustomAttribute<FieldAttr>();
}
}
Usage:
public class Program
{
public static void Main()
{
TestObject test = new TestObject();
Console.WriteLine(test.GetFieldAttr(() => test.testfld1).Text);
Console.WriteLine(test.GetFieldAttr(() => test.testfld2).Text);
Console.WriteLine(test.GetFieldAttr(() => test.testfld3).Text);
}
}
Uses:
using System;
using System.Linq;
using System.Reflection;
using System.Linq.Expressions;
I have implemented interfaces to protect the GetFieldAttr method
#Sulman22: Thnx for the response!

HashSet<T> quickly checking if identity exists by T.identity

I have an entity called Feature which contains a value identity called FeatureIdentity.
I have a list of these entities, and i want to quickly determine if the identity already exists.
The kicker is i need to be able to compare by the FeatureIdentity and not be the Feature, the Contains procedure on lists is checking against a provided T parameter.
So I am currently doing the code:
public class SomeClass
{
HashSet<Feature> features = new HashSet<Feature>();
public void SetRequirement(FeatureIdentity feature, FeatureIdentity requires)
{
if (ContainsFeature(feature) == false || ContainsFeature(requires) == false)
{
// throw
}
this.requirements.Add(feature, requires);
}
bool ContainsFeature(FeatureIdentity identity)
{
return this.features.Where(x => x.Id.Equals(identity)).Count() > 0;
}
}
Does Linq optimize this, or is this there a correct optimal way of checking if the item exists?
public class Feature
{
public Feature(FeatureIdentity id, string name)
{
this.id = id;
this.name = name;
}
FeatureIdentity id;
string name;
FeatureIdentity Id
{
get { return this.id; }
}
}
public class FeatureIdentity : IEquatable<FeatureIdentity>
{
private readonly string sku;
public FeatureIdentity(string sku)
{
this.sku = sku;
}
public bool Equals(FeatureIdentity other)
{
return this.sku == other.sku;
}
public string Sku
{
get { return this.sku; }
}
public override int GetHashCode()
{
return this.sku.GetHashCode();
}
}
with ctor public HashSet(), HashSet<Feature> is using EqualityComparer<Feature>.Default as default Comparer.
if you use HashSet<Feature>, you should implement IEquatable<Feature> and override GetHashCode.
public class Feature: IEquatable<Feature>
{
public bool Equals(Feature other)
{
return this.id.Equals(other.id);
}
public override int GetHashCode()
{
return this.id.GetHashCode();
}
}
then you can try following workaround which waster a temp object from heap.
bool ContainsFeature(FeatureIdentity identity)
{
return this.features.Contain(new Feature(identity, null));
}

Detecting attributes on a class to infer property?

I am not too familiar with reflection, however, would it be possible to implement a method that will return an object if that class has a property associated with a certain attribute?
I thought it might make this following implementation not being required
public interface IEntity
{
object ID { get; }
}
public class Person : IEntity
{
[Key]
public int PersonID { get; }
public string Name { get; set; }
public int Age { get; set; }
object IEntity.ID
{
get { return PersonID; }
}
}
So instead of implementing 'IEntity' for every class, you can just do something like this:
public abstract class EntityBase
{
public object ID { get { return FindPrimaryKey(); } }
protected object FindPrimaryKey()
{
object key = null;
try
{
//Reflection magic
}
catch (Exception) { }
return key;
}
}
This would just save some time instead of having to go through all code-first generated classes and implementing this small feature.
Yes, that can definitely be done. Consider the following code:
protected object FindPrimaryKey()
{
object key = null;
var prop = this.GetType()
.GetProperties()
.Where(p => Attribute.IsDefined(p, typeof(Key)))
if (prop != null) { key = prop.GetValue(this); }
return key;
}
However, I would recommend caching that value. Add a private field for the key value:
object _keyValue;
and then set that:
protected void FindPrimaryKey()
{
var prop = this.GetType()
.GetProperties()
.Where(p => Attribute.IsDefined(p, typeof(Key)))
if (prop != null) { _keyValue = prop.GetValue(this); }
}
and then return that instead:
public object ID { get { return _keyValue; } }

Writing my first DSL in C# and getting hung up on func<T> & Action

I'm taking a crack at writing my first DSL for a simple tool at work. I'm using the builder pattern to setup the complex parent object but am running into brick walls for building out the child collections of the parent object. Here's a sample:
Use:
var myMorningCoffee = Coffee.Make.WithCream().WithOuncesToServe(16);
Sample with closure (I think that's what they're called):
var myMorningCoffee = Coffee.Make.WithCream().PourIn(
x => {
x.ShotOfExpresso.AtTemperature(100);
x.ShotOfExpresso.AtTemperature(100).OfPremiumType();
}
).WithOuncesToServe(16);
Sample class (without the child PourIn() method as this is what I'm trying to figure out.)
public class Coffee
{
private bool _cream;
public Coffee Make { get new Coffee(); }
public Coffee WithCream()
{
_cream = true;
return this;
}
public Coffee WithOuncesToServe(int ounces)
{
_ounces = ounces;
return this;
}
}
So in my app for work I have the complex object building just fine, but I can't for the life of me figure out how to get the lambda coded for the sub collection on the parent object. (in this example it's the shots (child collection) of expresso).
Perhaps I'm confusing concepts here and I don't mind being set straight; however, I really like how this reads and would like to figure out how to get this working.
Thanks,
Sam
Ok, so I figured out how to write my DSL using an additional expression builder. This is how I wanted my DSL to read:
var myPreferredCoffeeFromStarbucks =
Coffee.Make.WithCream().PourIn(
x =>
{
x.ShotOfExpresso().AtTemperature(100);
x.ShotOfExpresso().AtTemperature(100).OfPremiumType();
}
).ACupSizeInOunces(16);
Here's my passing test:
[TestFixture]
public class CoffeeTests
{
[Test]
public void Can_Create_A_Caramel_Macchiato()
{
var myPreferredCoffeeFromStarbucks =
Coffee.Make.WithCream().PourIn(
x =>
{
x.ShotOfExpresso().AtTemperature(100);
x.ShotOfExpresso().AtTemperature(100).OfPremiumType();
}
).ACupSizeInOunces(16);
Assert.IsTrue(myPreferredCoffeeFromStarbucks.expressoExpressions[0].ExpressoShots.Count == 2);
Assert.IsTrue(myPreferredCoffeeFromStarbucks.expressoExpressions[0].ExpressoShots.Dequeue().IsOfPremiumType == true);
Assert.IsTrue(myPreferredCoffeeFromStarbucks.expressoExpressions[0].ExpressoShots.Dequeue().IsOfPremiumType == false);
Assert.IsTrue(myPreferredCoffeeFromStarbucks.CupSizeInOunces.Equals(16));
}
}
And here's my CoffeeExpressionBuilder DSL class(s):
public class Coffee
{
public List<ExpressoExpressionBuilder> expressoExpressions { get; private set; }
public bool HasCream { get; private set; }
public int CupSizeInOunces { get; private set; }
public static Coffee Make
{
get
{
var coffee = new Coffee
{
expressoExpressions = new List<ExpressoExpressionBuilder>()
};
return coffee;
}
}
public Coffee WithCream()
{
HasCream = true;
return this;
}
public Coffee ACupSizeInOunces(int ounces)
{
CupSizeInOunces = ounces;
return this;
}
public Coffee PourIn(Action<ExpressoExpressionBuilder> action)
{
var expression = new ExpressoExpressionBuilder();
action.Invoke(expression);
expressoExpressions.Add(expression);
return this;
}
}
public class ExpressoExpressionBuilder
{
public readonly Queue<ExpressoExpression> ExpressoShots =
new Queue<ExpressoExpression>();
public ExpressoExpressionBuilder ShotOfExpresso()
{
var shot = new ExpressoExpression();
ExpressoShots.Enqueue(shot);
return this;
}
public ExpressoExpressionBuilder AtTemperature(int temp)
{
var recentlyAddedShot = ExpressoShots.Peek();
recentlyAddedShot.Temperature = temp;
return this;
}
public ExpressoExpressionBuilder OfPremiumType()
{
var recentlyAddedShot = ExpressoShots.Peek();
recentlyAddedShot.IsOfPremiumType = true;
return this;
}
}
public class ExpressoExpression
{
public int Temperature { get; set; }
public bool IsOfPremiumType { get; set; }
public ExpressoExpression()
{
Temperature = 0;
IsOfPremiumType = false;
}
}
Any and all suggestions are welcome.
What if .IncludeApps accepted an array of AppRegistrations
IncludeApps(params IAppRegistration[] apps)
then
public static class App
{
public static IAppRegistration IncludeAppFor(AppType type)
{
return new AppRegistration(type);
}
}
public class AppRegistration
{
private AppType _type;
private bool _cost;
public AppRegistration(AppType type)
{
_type = type;
}
public AppRegistration AtNoCost()
{
_cost = 0;
return this;
}
}
so eventually it would look like this...
.IncludeApps
(
App.IncludeAppFor(AppType.Any),
App.IncludeAppFor(AppType.Any).AtNoCost()
)
Inside your IncludeApps method you would inspect the registrations and create the objects as required.
To go the delegate route maybe something like this would work?
var aPhone = MyPhone.Create;
MyPhone.Create.IncludeApps
(
x =>
{
x.IncludeAppFor(new object());
}
);
class MyPhone
{
public MyPhone IncludeApps(Action<MyPhone> includeCommand)
{
includeCommand.Invoke(this);
return this;
}
}
If you aren't set on the delegate route maybe params would work?
var anotherPhone = MyPhone.Create.IncludeApps(
new IncludeAppClass(AppType.Math),
new IncludeAppClass(AppType.Entertainment).AtNoCost());
class MyPhone
{
internal MyPhone IncludeApps(params IncludeAppClass[] includeThese)
{
if (includeThese == null)
{
return this;
}
foreach (var item in includeThese)
{
this.Apps.Add(Item);
}
return this;
}
}

Categories