在Entity Framework代码中添加自定义属性属性 [英] Adding custom property attributes in Entity Framework code

查看:167
本文介绍了在Entity Framework代码中添加自定义属性属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在EF生成的代码中为属性添加自定义属性?我唯一可以看到的一个合理的解决方案是提出一个自定义的T4模板。然而,由于属性的性质,将无法确定每个EF属性的正确属性参数。

解决方案

您可以通过指定镜像属性的元数据类型,并简单地用于归因。 b
$ b

  [MetadataType(typeof(Dinner_Validation))] 
public partial class Dinner
{}

public class Dinner_Validation
{
[必需]
public string标题{get;组; }
}

史蒂夫·史密斯博客关于它这里



不幸的是,上面的方法是脆弱的重构。另一个选择是使用新的POCO实体。这些避免了编译时代码的产生,就我所知。我还没有使用它们,所以不能评论任何陷阱或权衡。


Is there any way to add custom attributes to properties in EF generated code? The only thing I can see as a plausible solution would be to come up with a custom T4 template. However, because of the nature of the attribute it would be impossible to determine the correct attribute parameter per EF property.

解决方案

You can do this by specifying a metadata type that mirrors the properties and is used simply for attribution.

[MetadataType(typeof(Dinner_Validation))] 
public partial class Dinner 
{} 

public class Dinner_Validation 
{ 
    [Required] 
    public string Title { get; set; } 
}

Steve Smith blogs about it here.

Unfortunately the above approach is brittle to refactoring. Another option is to use the new POCO entities. These avoid compile-time code generation altogether as far as I can tell. I haven't used them yet so can't comment on any pitfalls or tradeoffs.

这篇关于在Entity Framework代码中添加自定义属性属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆