Entity Framework Code First Casting Columns

六月ゝ 毕业季﹏ 提交于 2019-12-23 03:25:40

问题


I have an class

public class Foo
{
    public int UserId { get; set; }
}

and I'm using the code first fluent mapping to map this to the database.

Property(i => i.UserId)
            .HasColumnName("userno");

the only problem is that userno is actually a char(10) in the database. How do I go about casting or converting this type? as I currently get this error.

The 'UserId' property on 'Foo' could not be set to a 'String' value. You must set this property to a non-null value of type 'Int32'.

Thanks


回答1:


Entity framework doesn't have any support for type conversion in mapping so the only valid mapped property in your scenario is:

public class Foo
{
    public string UserId { get; set; }
}

If you want int property as well you must do:

public class Foo
{
    public string UserId { get; set; }

    public int UserIntId 
    {
       get { return Int32.Parse(UserId); }
       set { UserId = value.ToString(); }
    }
}

And add this to your mapping:

Ignore(i => i.UserIntId);

You can play with accessibility of UserId property but be aware that accessibility also affects if your mapping actually sees the property. If it doesn't you will not have UserId mapped at all.



来源:https://stackoverflow.com/questions/6909309/entity-framework-code-first-casting-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!