Search code examples
c#.netentity-frameworkentity

Mapping custom POCO in Entity Framework 4


So I have a small issue with converting a string to a boolean when EF maps to my POCO. I created custom POCOs and I have one that has a boolean property called "IsActive". But, in the database the tables column "IsActive", that maps to the POCOs property, is a string. It's either 'Y' or 'N'.

EF doesn't like this, so I'm wondering if there's a way to tell it to convert the string to a boolean through a custom method?? Thanks!


Solution

  • Have not tested it by myself. Link

    Create complex type definition in your edmx.

    <ComplexType Name="IsActiveWrapper" > 
              <Property Type="string" Name="Value" Nullable="false" /> 
    </ComplexType>
    

    Create complex type

    public class IsActiveWrapper
    {
        private bool isActive;
    
        public string Value
        {
            get
            {
                return isActive ? "Y" : "N";
            }
    
            set
            {
                isActive = "Y".Equals(value);
            }
        }
    
        public bool IsActive
        {
            get { return isActive; }
            set { isActive = value; }
        }
    
        public static implicit operator IsActiveWrapper(bool isActive)
        {
            return new IsActiveWrapper { IsActive = isActive };
        }
    
        public static implicit operator bool(IsActiveWrapper wrap)
        {
            if (wrap == null) return false;
            return wrap.IsActive;
        }
    }
    

    Now you can do something like this

    public class TestIsActive
    {
        public virtual IsActiveWrapper IsActive { get; set; }
    }
    var test = new TestIsActive { IsActive = true };