实体框架代码优先铸造列

发布于 2024-11-27 17:18:03 字数 393 浏览 5 评论 0原文

我有一个类

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

,我正在使用代码优先流畅映射将其映射到数据库。

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

唯一的问题是 userno 实际上是数据库中的 char(10) 。我该如何转换或转换这种类型?因为我目前收到此错误。

“Foo”的“UserId”属性无法设置为“String”值。 您必须将此属性设置为“Int32”类型的非空值。

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

自我难过 2024-12-04 17:18:03

实体框架不支持映射中的类型转换,因此您的场景中唯一有效的映射属性是:

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

如果您还需要 int 属性,则必须执行以下操作:

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

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

其添加到您的映射中:

Ignore(i => i.UserIntId);

并将 可以使用 UserId 属性的可访问性,但请注意,可访问性也会影响您的映射是否实际看到该属性。如果没有,您将根本不会映射 UserId

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文