简体   繁体   中英

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!

Have not tested it by myself. http://blogs.msdn.com/b/alexj/archive/2009/06/05/tip-23-how-to-fake-enums-in-ef-4.aspx

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 };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM