添加代码访问安全属性,而无需修改ADO.Net实体数据模型向导生成的代码

时间:2018-07-22 04:32:21

标签: c# entity-framework-6 override ado.net-entity-data-model code-access-security

我正在使用ADO.Net Entity Data Model项目对我的数据库进行反向工程。自动为DbContext创建的.cs页面之一将覆盖OnModelCreating方法。该页面上有注释,警告我不要更改文件上的代码,因为如果重新生成代码,它将被覆盖。参见下面的图1。

我需要将以下属性添加到OnModelCreating方法中: [System.Security.SecurityCriticalAttribute]

是否可以在不修改向导生成的代码的情况下添加代码访问安全性属性?

到目前为止,我已经尝试使用部分类(图2),但是在运行时它会引发以下错误: MyApp.Models.MyDbContext.OnModelCreating(System.Data.Entity.DbModelBuilder)'. Security accessibility of the overriding method must match the security accessibility of the method being overriden.

图1

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace MyApp.Models
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;

    public partial class MyDbContext : DbContext
    {
        public MyDbContext ()
            : base("name=MyDbContext ")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public virtual DbSet<LOOKUP_LOG> LOOKUP_LOG { get; set; }
        public virtual DbSet<ITEM_IDENTIFICATION> ITEM_IDENTIFICATION { get; set; }
    }
}

图2

[SecurityCriticalAttribute]
public class EntityHelper : MyDbContext
{
    public static MyDbContext GetDbContext(String connString)
    {
        var _context = new MyDbContext();

        var entityBuilder = new EntityConnectionStringBuilder();
        entityBuilder.Provider = "Oracle.ManagedDataAccess.Client";
        entityBuilder.ProviderConnectionString = connString;
        entityBuilder.Metadata = @"res://*/Models.MyDB.csdl|
                                   res://*/Models.MyDB.ssdl|
                                   res://*/Models.MyDB.msl";

        _context = new MyDbContext(entityBuilder.ToString());

        return _context;
    }

    [System.Security.SecurityCriticalAttribute]
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }
}

[SecurityCriticalAttribute]
public partial class MyDbContext : DbContext
{
    public MyDbContext(String connectionString)
        : base(connectionString)
    {
    }
}

0 个答案:

没有答案