我首先使用实体框架4.3.1代码进行显式迁移。如何在实体配置类或迁移中添加列的描述,以便它最终成为SQL Server(例如2008 R2)中列的描述?
我知道我可能可以为DbMigration
类编写一个扩展方法,该方法将sp_updateextendedproperty
或sp_addextendedproperty
过程调用注册为迁移事务中的sql迁移操作,并在迁移Up
方法中创建表后调用该扩展。但是,是否有一种优雅的内置方式,我还没有发现?如果有一个属性,迁移'改变检测逻辑可以拾取并生成搭建迁移中的适当方法调用。
6条答案
按热度按时间nbysray51#
我也需要这个。所以我花了一天时间,它就在这里:
在您的
Migrations/Configuration.cs
文件中,将以下代码添加到Seed
方法的末尾:然后在软件包管理器控制台中键入
update-database
并按Enter键。代码使用实体类属性上的
[Display(Name="Description here")]
属性来设置描述。请报告任何错误或提出改进建议。
"感谢"
我已经使用这些代码从其他人,我想说谢谢:
adding a column description
Check if a class is derived from a generic class
Get Database Table Name from Entity Framework MetaData
Generics in C#, using type of a variable as parameter
vsaztqbk2#
Note对当前的答案非常满意(但这是工作的 prop !),我希望有一种方法来拉我的类中现有的注解标记,而不是使用属性。在我看来,我不知道为什么微软不支持这一点,因为它似乎显然应该存在!
首先,打开XML文档文件:项目属性-〉生成-〉XML文档文件-〉App_Data\您的项目名称.XML
其次,将该文件作为嵌入式资源包括在内。生成您的项目,转到App_Data,显示隐藏文件并包括生成的XML文件。选择“嵌入式资源”和“复制(如果较新(这是可选的,你可以显式地指定路径,但在我看来这更简洁)。注意,你必须使用这个方法,因为标记不存在于程序集中,并且将使您不必查找XML的存储位置。
下面是代码实现,它是已接受答案的修改版本:
以及从visual studio生成的XML文档文件中获取注解标记的类:
jfewjypa3#
你可以不使用
ExceuteSqlCommand
方法。在这里,你可以显式地定义你想添加到你的表中的任何 meta属性。http://msdn.microsoft.com/en-us/library/system.data.entity.database.executesqlcommand(v=vs.103).aspx
2nc8po8w4#
谢谢你Mahmoodvcs先生的伟大解决方案。请允许我修改它,只需将“显示属性”替换为“描述属性”,而不是使用:
您将用途:
所以它也包括table。
yfwxisqw5#
虽然问题是关于EF4的,但此答案针对的是EF6,考虑到自提出问题以来经过的时间,这应该是适当的。
我认为注解属于迁移
Up
和Down
方法,而不是某个Seed
方法。因此,正如@MichaelBrown所建议的,从启用XML文档输出开始,并将文档文件作为嵌入式资源包含在项目中。
然后,让我们使用
Convention
将注解转换为表/列注解。对于多行注解和去除过多的空格等方面,需要进行一些调整。在
OnModelCreating
方法中注册约定。预期结果:创建新迁移时,注解将作为注解包括在内,如
接下来是第二部分:调整SQL生成器以从注解创建注解。
这是针对Oracle的,但MS Sql应该非常相似
在
DbMigrationsConfiguration
构造函数中,注册新的代码生成器(同样,这是Oracle特有的,但对于其他SQL提供程序也是类似的)预期结果:
Up
和Down
方法中的注解注解被转换为SQL语句,这些语句可更改数据库中的注解。dy2hfwbg6#
现在到了2023年,我已经将Mahmood Dehghan提供的解决方案更新为.Net 6和Entity Framework Core 6 here,并做了一些小的修改,以包括来自基类的属性(如果主类中不存在),并将扩展属性添加到表中。