我需要为我的MVC项目(网络应用程序)中的所有表添加审核列(创建者,创建者,修改者和修改者)。我想到了一个包含这4列的基类,并继承所有其他类。但是我使用的是数据库优先方法,因此EF生成了所有类。我不确定如何添加审核列和基类继承。
答案 0 :(得分:0)
我认为无法首先通过EF数据库执行所需的操作。但是,为了将特定字段添加到数据库的所有表中,您可以对Sql Server中的每个字段使用以下代码,然后更新您的EF模型。
DECLARE @TableName VARCHAR(100)
DECLARE @TableSchema VARCHAR(100)
DECLARE @COLUMN_NAME VARCHAR(50)
SET @COLUMN_NAME='CreatedOn'
DECLARE @COLUMN_DATATYPE VARCHAR(50)
SET @COLUMN_DATATYPE='DateTime'
DECLARE CUR CURSOR FOR
SELECT TABLE_SCHEMA,
TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
OPEN CUR
FETCH NEXT FROM CUR INTO @TableSchema,@TableName
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @SQL NVARCHAR(MAX)
SET @SQL=NULL
IF NOT EXISTS ( SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME=@TableName AND COLUMN_NAME = @COLUMN_NAME and Table_Schema=@TableSchema)
BEGIN
SET @SQL='ALTER TABLE '+ @TableSchema+'.'+ @TableName +' ADD '+ @COLUMN_NAME + ' '+ @COLUMN_DATATYPE
PRINT @SQL
EXEC(@SQL)
END
IF EXISTS ( SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME=@TableName AND COLUMN_NAME=@COLUMN_NAME and Table_Schema=@TableSchema)
BEGIN
PRINT 'Column Already exists in Table'
END
FETCH NEXT FROM CUR INTO @TableSchema,@TableName
END
CLOSE CUR
DEALLOCATE CUR
答案 1 :(得分:0)
数据库首先意味着您必须手动将所有字段添加到数据库,并且AFAIK没有继承。您可以编写一个SQL脚本来添加这些列。正如Mahyar所说。但是您仍然缺少继承。
或者您先切换到代码。然后,您可以定义一个接口并用代码处理审核。如here所示。 例如,我使用以下界面:
/// <summary>
/// Adds auditing properties to an entity.
/// </summary>
public interface IAuditedEntity
{
/// <summary>
/// Date and time of the entity's creation. Usually in UTC.
/// </summary>
/// <remarks>Best set via a <see cref="ITimeProvider"/>.</remarks>
DateTime DateCreated { get; set; }
/// <summary>
/// Identification who created this instance.
/// </summary>
/// <remarks>Best set via a <see cref="ICurrentUserIdProvider"/>.</remarks>
string CreatedBy { get; set; }
/// <summary>
/// Date and time of last modification. Usually in UTC.
/// </summary>
/// <remarks>Best set via a <see cref="ITimeProvider"/>.</remarks>
DateTime? DateModified { get; set; }
/// <summary>
/// Last one modifiying this instance.
/// </summary>
/// <remarks>Best set via a <see cref="ICurrentUserIdProvider"/>.</remarks>
string ModifiedBy { get; set; }
}
用户提供者界面的定义如下:
/// <summary>
/// Interface for providing the current user's id.
/// </summary>
public interface ICurrentUserIdProvider
{
/// <summary>
/// Get the id of the curent user.
/// </summary>
/// <returns></returns>
string GetCurrentUserId();
}
出于测试目的,您现在可以使用ambient context/service交付当前用户或您需要测试逻辑的任何用户。