enums in EF code first - entity-framework-4

please, how to work with enums in Entity Framework code first. i want that in my class "Annonce" i can have this proprety
public Status EtatAnnonce { get; set; }
and Status is defined like this
public enum Status
{
Pending,
Approved
}

You need to create a converter field to store the value as int in the database.
public int MyEnumValueInt {get;set;}
[NotMapped]
public MyEnum MyEnumValue
{
get{ return (MyEnum)MyEnumValueInt;
set{ MyEnumValueInt = (int)value;
}
Note: The enum support will be improved in EF 5.

Will point you towards
EF5 does not create enum columns
To give a summary of enum support in Entity Framework code first:
EF4: Not supported
EF5: only supported if you are targeting .net framework 4.5 and higher
EF6: only supported if you target .net 4.0 and higher
Cheers!

I've answered two questions regarding Enums in EF; these should help you along:
Enums with EF code-first - standard method to seeding DB and then using?
and
EF 4.1 Code First - map enum wrapper as complex type

You can use private properties in your model to map your data to whatever property type you want.
// Model
public class Piece
{
// Subclass Piece to add mappings for private properties
public class PieceConfig : EntityTypeConfiguration<Piece>
{
public PieceConfig()
{
Property(b => b.dbtype); // needed for EF to see the private property
}
}
[Column("type", TypeName = "VARCHAR")]
private string dbtype { get; set; }
[NotMapped]
public PIECE type
{
get { return (PIECE)Enum.Parse(typeof(PIECE), dbtype); }
set { dbtype= value.ToString(); }
}
}
Then you just need to add the configuration to your OnModelCreating method
modelBuilder.Configurations.Add(new Piece.PieceConfig());

Related

Propery injection not working with Prism Unity

We have a WPF application using Prism (7.2.0.1422) and Unity as the DI container. I have the following class where I am attempting to use Unity Property injection
public class LocalizedDescriptionAttribute : DescriptionAttribute
{
[Dependency]
IStringResource _stringResource { get; set; }
string _resourceKey;
public LocalizedDescriptionAttribute(string resourceKey)
{
_resourceKey = resourceKey;
}
public override string Description
{
get
{
string description = _stringResource.GetString(_resourceKey);
return string.IsNullOrWhiteSpace(description) ? string.Format("[[{ 0}]]", _resourceKey) : description;
}
}
}
_stringResource is always null. I have registered the type as a singleton like this in RegisterTypes
containerRegistry.RegisterSingleton<IStringResource, StringResource>();
Anyone any ideas.
Thanks
Based on the name of the class, I assume it's an actual attribute? That cannot have anything injected by Unity, because the container can only inject into instances it creates itself.
You can, however, use the container from the attribute's code through a detour: the CommonServiceLocator. That's a static class that you only use if you have to, and this may be one of the rare cases where it's a good idea. You can use it to resolve the IStringResource from the container at runtime.

How can I use Automapper to map all zero int values to null values for nullable int targets?

I use int? for all my required 'FK' properties in ViewModels. This gives me an easy way of specifying on a Create view model that a value is nullable and must be assigned a value to satisfy the Required attribute.
My problem comes in because I create the domain model entity first, using a domain factory, then map it to the view model. Now, many of the nullable ints in the view model get assigned 0 from non-nullable ints in the domain model. I would prefer not to build the new entity in the view model and only map it back to the domain model to avoid his. What else can I do? i'm sure there is som Automapper voodoo that can help me.
EDIT: you dont need to do any of this, but i thought i'd leave it here for people looking for a similar solution. really all you have to do is just provide a mapping from int to int? like this: Mapper.Map<int, int?>()
in that case, I believe you could use a custom type converter, which inherits from automappers ITypeConverter. This code works, I've run it through .NET Fiddle:
using System;
using AutoMapper;
public class Program
{
public void Main()
{
CreateMappings();
var vm = Mapper.Map<MyThingWithInt, MyThingWithNullInt>(new MyThingWithInt());
if (vm.intProp.HasValue)
{
Console.WriteLine("Value is not NULL!");
}
else
{
Console.WriteLine("Value is NULL!");
}
}
public void CreateMappings()
{
Mapper.CreateMap<int, int?>().ConvertUsing(new ZeroToNullIntTypeConverter ());
Mapper.CreateMap<MyThingWithInt, MyThingWithNullInt>();
}
public class ZeroToNullIntTypeConverter : ITypeConverter<int, int?>
{
public int? Convert(ResolutionContext ctx)
{
if((int)ctx.SourceValue == 0)
{
return null;
}
else
{
return (int)ctx.SourceValue;
}
}
}
public class MyThingWithInt
{
public int intProp = 0;
}
public class MyThingWithNullInt
{
public int? intProp {get;set;}
}
}
You can always use the .ForMember() method on your mapping. Something like this:
Mapper
.CreateMap<Entity, EntityDto>()
.ForMember(
dest => dest.MyNullableIntProperty,
opt => opt.MapFrom(src => 0)
);

Should the EnumDataTypeAttribute work correctly in .NET 4.0 using Entity Framework?

I have an enumeration which I'd like to persist as a value of some sort into the underlying database so that I can bring it back and forth.
I have read some articles that suggest to create a enumeration wrapper with static implicit operators defined, mapped using a ComplexType object mapping as described in the link below.
How to fake Enums in EF4
This solution works flawlessly! My thanks to Alex James.
Aside, I discovered of the EnumDataTypeAttribute Class which purpose seems to handle enums persistence through Entity Framework. I tried it and it doesn't seem to work at all. Here's a code sample.
public enum StreetDirection {
East
, None
, North
, NorthEast
, NorthWest
, South
, SouthEast
, SouthWest
, West
}
public enum StreetType {
Avenue
, Boulevard
, Court
, Crescent
, Drive
, Hill
, None
, Road
, Street
}
public class StreetTypeWrapper {
public int Value {
get {
return (int)t;
}
set {
t = (StreetType)value;
}
}
public StreetType EnumValue {
get {
return t;
}
set {
t = value;
}
}
public static implicit operator int(StreetTypeWrapper w) {
return w.Value;
}
public static implicit operator StreetType(StreetTypeWrapper w) {
return w == null ? StreetType.None : w.EnumValue;
}
public static implicit operator StreetTypeWrapper(int i) {
return new StreetTypeWrapper() { Value = i };
}
public static implicit operator StreetTypeWrapper(StreetType t) {
return new StreetTypeWrapper() { EnumValue = t };
}
private StreetType t;
}
public class Street {
[EnumDataType(typeof(StreetDirection))]
public StreetDirection Direction { get; set; }
public string Name { get; set; }
public int StreetId { get; set; }
public StreetTypeWrapper Type { get; set; }
}
public class StreetTypeMapping
: ComplexTypeConfiguration<StreetTypeWrapper> {
public StreetTypeMapping() {
Property(o => o.Value)
.HasColumnName("StreetType");
}
}
Now, if I believe and/or understanding correctly what MSDN says about the EnumDataTypeAttribute class, the Direction property should get persisted into the database. Well, it doesn't! I can't find a reason for this, except that EF doesn't support enums persistence. As for the StreetTypeWrapper and its StreetTypeMapping class, it does work flawlessly.
Are there any clue why the EnumDataType shouldn't work as expected?
This is because of design flaw in .NET framework. .NET framework contains famous System.ComponentModel.DataAnnotations namespace where multiple different attributes are defined. Many different parts of .NET framework are using this namespace but they are using it to achieve different tasks and every such part use only some subset of attributes. This causes a lot of confusion.
EnumDataTypeAttribute is such example. This attribute is only for ASP.NET Dynamic Data. It allows you to mark int property with this attribute and automatically generated UI will show drop down with enum values instead of textbox for numeric values. So there is mapping from enum to int but it is in UI layer not in model / persistence layer.

How to inject dependencies in Collection form?

How do I wire up dependencies where the dependency is in the form of a collection ??
For Example:
public class Ninja {
public List<IShuriken> Shurikens {get;set;}
public IKatana Katana {get;set;}
public void Attack()
{
// some code goes here to use weapons and kill people
}
}
How do i use a container like Ninject in a case like this ??
EDIT: I am not talking specifically about Ninject but thats the DI/IOC I use the most. :)
You can Bind a closed type List<X> ToConstant(), ToMethod() etc.
But you'd have to supply more detail as to what you want in the list or I'd just be engaging in idle speculation as to exactly what you want.
EDIT in response to yours and your comment: If you're dealing with 'Unknown' or loose dependencies, then MEF does lots of stuff in that direction.
[In general with DI] If you're doing something internally and it's a more 'Known' / fixed / complex resolution mechanism, you're better off modelling something like this by having a Repository or other coordinating object that will manage the list that you can request subsets and/or other projections of on an as-needed basis.
[If you're interested in specific mechanisms in Niject] You'd be crazy not to download the source and do a grep/FIF/Shift-Ctrl-Q for List to find out the real story though - the code is clean and neat and the Tests provide examples.
For example, you can Bind multiple items to an interface and then have them added into a collection for you automatically:-
namespace Ninject.Tests.Integration.EnumerableDependenciesTests {
public class WhenServiceRequestsUnconstrainedListOfDependencies
{
[Fact]
public void ServiceIsInjectedWithListOfAllAvailableDependencies()
{
kernel.Bind<IParent>().To<RequestsList>();
kernel.Bind<IChild>().To<ChildA>();
kernel.Bind<IChild>().To<ChildB>();
var parent = kernel.Get<IParent>();
VerifyInjection( parent );
}
protected override void VerifyInjection( IParent parent )
{
parent.ShouldNotBeNull();
parent.Children.ShouldNotBeNull();
parent.Children.Count.ShouldBe( 2 );
parent.Children[0].ShouldBeInstanceOf<ChildA>();
parent.Children[1].ShouldBeInstanceOf<ChildB>();
}
}
public class RequestsList : IParent
{
public IList<IChild> Children { get; private set; }
public RequestsList( List<IChild> children )
{
Children = children;
}
}
public interface IChild { }
public class ChildA : IChild { }
public class ChildB : IChild { }
public interface IParent
{
IList<IChild> Children { get; }
}
}
In Autofac you'd use an IEnumerable constructor dependency:
public class Ninja {
public Ninja(IEnumerable<IShuriken> shurikens, IKatana katana)
{
// ...
}
Autofac will find any available shurikens and provide them to the constructor automatically.
I don't know about Ninject. in Castle Windsor, you'd use ListResolver and that would provide all implementations of IShuriken.

StructureMap: Configure concrete classes at run time?

I know that Concrete Types can be configured with Structure Map the following way:
ForRequestedType<Rule>().TheDefault.Is.Object(new ColorRule("Green"));
This works if you know the type ahead of time. I want to do it at run time, and there does not seem to be a way. Can some one enlighten me? What I want to do is something like the following: (This appears to be not supported by structure map)
ForRequestedType(typeof(Rule)).TheDefault.Is.Object(new ColorRule("Green"));
The reason for this is because I'm working on a wrapper for structure-map's configuration. And I will not know the type ahead of time. For the .Object(new ColorRule("Green")) I am going to be passing in a delegate instead, which would actually construct the object on request.
Recently Jeremy added the ability to configure a Func as a builder for your type. Here is an example of using a delegate/lambda as your builder.
public interface IRule
{
string Color { get; set; }
}
public class ColorfulRule : IRule
{
public string Color { get; set; }
public ColorfulRule(string color)
{
Color = color;
}
}
[TestFixture]
public class configuring_delegates
{
[Test]
public void test()
{
var color = "green";
Func<IRule> builder = () => new ColorfulRule(color);
var container = new Container(cfg=>
{
cfg.For<IRule>().Use(builder);
});
container.GetInstance<IRule>().Color.ShouldEqual("green");
color = "blue";
container.GetInstance<IRule>().Color.ShouldEqual("blue");
}
}

Resources