【问题标题】:.Net entity framework Ignore constraints based on ConnectionString.Net实体框架忽略基于ConnectionString的约束
【发布时间】:2018-05-03 09:52:51
【问题描述】:

我有一个DBContext 代码优先方法。它将接受连接字符串作为参数。

可以根据用户提供的连接字符串忽略外键约束吗?

public class EFDbContext : DbContext{
     public EFDbContext(string connection="Default"):base(connection)
     {
     }
     public DbSet<Contact> Contact { get; set; }
}

我的Contact 类如下所示:

public class Contact
{     
    [Key]
    public long ContactId { get; set; }


    //Foreign key to Contact
    [ForeignKey("SystemUsers")] //**Need to ignore this constaint If DB is NoRelationsDB**
    public Guid UserId { get; set; }
    public virtual SystemUsers SystemUsers { get; set; }
}

我对实体的用法是:

 EFDbContext context=new EFDbContext();
 EFDbContext context1=new EFDbContext("NoRelationsDB"); //If the connection string is this then we have to ignore all the constraints in Tables.

【问题讨论】:

  • 如果你想忽略约束,拥有它们有什么意义?约束是有原因的。您有时想忽略它们的原因是什么?不知何故,它闻起来像是设计缺陷。

标签: asp.net-mvc entity-framework connection-string


【解决方案1】:

可以根据用户提供的连接字符串忽略外键约束吗?

没有。外键约束是数据库中模式设计的一部分。将对所有用户强制(或不强制)约束。

在 SQL Server 中,有几种情况会忽略约束。如果将约束标记为 NOT FOR REPLICATION,则允许复制代理绕过约束。如果您使用批量 API 加载数据,您可以选择跳过约束检查。

除此之外,您可以禁用所有约束、加载数据,然后重新启用它们。或者您可以使用触发器来强制执行参照完整性,并编写触发器以在某些条件下跳过检查。

【讨论】:

  • 用户以代码优先的方式使用不同的连接字符串。如果连接字符串指向不同的物理数据库,那你为什么要拒​​绝呢?阅读他的问题If DB is NoRelationsDB...
  • 单个 AppDomain 中相同 DbContext 类型的两个不同实例不能有不同的模型。 OnModelCreating() 只会在第一次创建 DbContext 类型的实例时运行。并且该模型对现有数据库中的 FK 约束没有影响。
  • 好的,你是对的,如果你编辑你的答案,我可以删除我的反对票。
猜你喜欢
  • 1970-01-01
  • 2014-03-29
  • 1970-01-01
  • 2014-07-17
  • 1970-01-01
  • 2012-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多