c# - 导航属性和级联删除

标签 c# entity-framework ef-code-first cascade navigation-properties

我正在使用 EF5 fluent-api 来尝试在多个表之间建立关系/约束,我希望这些关系包括删除时的级联,我认为我遗漏了一些简单的东西,因为我在下面尝试过,产生说错误。帖子很长,但 99% 的代码并不复杂,但在尝试重新初始化我的模型时收到下面提到的错误 - 存在一些预期的约束,但未找到。真的让我摸不着头脑......任何方向都将不胜感激。

namespace Deals.Core.DataAccess.Entities
{
   public abstract class Entity<TEntity> : IEntity<TEntity> where TEntity : Entity<TEntity>, new()
   {
      private bool isEmpty;

      protected Entity()
      {
         this.isEmpty = false;
      }

      public static TEntity Empty
      {
         get
         {
            return new TEntity() { IsEmpty = true };
         }
      }

      public bool Active { get; set; }
      public bool Deleted { get; set; }

      [NotMapped]
      public bool IsEmpty
      {
         get
         {
            return this.isEmpty;
         }

         protected set
         {
            this.isEmpty = value;
         }
      }

      public int Version { get; set; }
   }

   public class Site : Entity<Site>, ISite
   {
      public Guid Id { get; set; }
      public virtual ICollection<User> Users { get; set; }
      public virtual Survey Survey { get; set; }
   }

   public class Survey : Entity<Survey>, ISurvey
   { 
      public Guid Id { get; set; }
      public virtual Site Site { get; set; }
   }

   public class User : Entity<User>, IUser
   {
      public Guid Id { get; set; }
      public virtual UserProfile UserProfile { get; set; }
      public Guid SiteId { get; set; }
      public virtual Site Site { get; set; }
   }

   public class UserProfile : Entity<UserProfile>, IUserProfile
   {
      public Guid Id { get; set; }
      public virtual User User { get; set; }
   }
}

namespace Deals.Core.DataAccess.Models
{
   public class Context : DbContext, IContext
   {
      public DbSet<Site> Sites { get; set; }
      public DbSet<Survey> Surveys { get; set; }
      public DbSet<User> Users { get; set; }
      public DbSet<UserProfile> UserProfiles { get; set; }

      protected override void OnModelCreating(DbModelBuilder modelBuilder)
      {
         this.MapSite(modelBuilder);
         this.MapSurvey(modelBuilder);
         this.MapUser(modelBuilder);
         this.MapUserProfile(modelBuilder);

         Database.SetInitializer(new MigrateDatabaseToLatestVersion<Context, ContextConfiguration>());

         base.OnModelCreating(modelBuilder);
      }

      protected virtual void MapSite(DbModelBuilder modelBuilder)
      {
         // Ignore the IsEmpty property.
         this.MapEntity<Site>(modelBuilder);

         modelBuilder.Entity<Site>().HasKey(p => p.Id);
         modelBuilder.Entity<Site>().HasOptional(p => p.Survey);
         modelBuilder.Entity<Site>().HasOptional(p => p.Users);
      }

      protected virtual void MapUser(DbModelBuilder modelBuilder)
      {
         // Ignore the IsEmpty property.
         this.MapEntity<User>(modelBuilder);

         modelBuilder.Entity<User>().HasKey(p => p.Id);
         modelBuilder.Entity<User>().HasRequired(p => p.Site).WithMany(p => p.Users).HasForeignKey(p => p.SiteId);
      }

      protected virtual void MapUserProfile(DbModelBuilder modelBuilder)
      {
         // Ignore the IsEmpty property.
         this.MapEntity<UserProfile>(modelBuilder);

         modelBuilder.Entity<UserProfile>().HasKey(p => p.Id);

         // Why does adding .WillCascadeOnDelete() look for a user_id constraint on UserProfile that does not exist?
         //modelBuilder.Entity<UserProfile>().HasRequired(p => p.User).WithRequiredPrincipal(user => user.UserProfile);
         //// .WillCascadeOnDelete();
         modelBuilder.Entity<UserProfile>().HasRequired(p => p.User);
      }

      protected virtual void MapSurvey(DbModelBuilder modelBuilder)
      {
         // Ignore the IsEmpty property.
         this.MapEntity<Survey>(modelBuilder);

         modelBuilder.Entity<Survey>().HasKey(p => p.Id);
         modelBuilder.Entity<Survey>().HasRequired(p => p.Site);
         //modelBuilder.Entity<Site>().HasOptional(p => p.Survey).WithOptionalPrincipal().WillCascadeOnDelete();
         modelBuilder.Entity<Survey>().Property(p => p.SurveyXml).HasColumnType("xml").IsRequired();
      }

      #region Generic Mapping
      protected virtual void MapEntity<T>(DbModelBuilder modelBuilder) where T : Entity<T>, new()
      {
         // Ignore the IsEmpty property.
         modelBuilder.Entity<T>()
            .Ignore(p => p.IsEmpty);
      }

      #endregion Generic Mapping
   }
}

生成的 SQL:

create table [dbo].[Sites] (
    [Id] [uniqueidentifier] not null,
    [Url] [nvarchar](max) null,
    [Description] [nvarchar](max) null,
    [Active] [bit] not null,
    [Deleted] [bit] not null,
    [Version] [int] not null,
    primary key ([Id])
);
create table [dbo].[Surveys] (
    [Id] [uniqueidentifier] not null,
    [SurveyXml] [xml] not null,
    [Active] [bit] not null,
    [Deleted] [bit] not null,
    [Version] [int] not null,
    primary key ([Id])
);
create table [dbo].[Users] (
    [Id] [uniqueidentifier] not null,
    [UserName] [nvarchar](max) null,
    [Password] [nvarchar](max) null,
    [LastLogin] [datetime] not null,
    [SiteId] [uniqueidentifier] not null,
    [Active] [bit] not null,
    [Deleted] [bit] not null,
    [Version] [int] not null,
    primary key ([Id])
);
create table [dbo].[UserProfiles] (
    [Id] [uniqueidentifier] not null,
    [FirstName] [nvarchar](max) null,
    [LastName] [nvarchar](max) null,
    [MiddleInitial] [nvarchar](max) null,
    [Honorific] [nvarchar](max) null,
    [Email] [nvarchar](max) null,
    [Active] [bit] not null,
    [Deleted] [bit] not null,
    [Version] [int] not null,
    primary key ([Id])
);

Сan't get "on delete cascade"here:

alter table [dbo].[Surveys] add constraint [Site_Survey] foreign key ([Id]) references [dbo].[Sites]([Id]); 

这很好:

alter table [dbo].[Users] add constraint [User_Site] foreign key ([SiteId]) references [dbo].[Sites]([Id]) on delete cascade;

无法在此处获取“on delete cascade”:

alter table [dbo].[UserProfiles] add constraint [UserProfile_User] foreign key ([Id]) references [dbo].[Users]([Id]); 

如果我这样做:

 modelBuilder.Entity<UserProfile>()
      .HasRequired(p => // p.User)
      .WithRequiredPrincipal(user => user.UserProfile)
      .WillCascadeOnDelete();

 // Instead of this:
 modelBuilder.Entity<UserProfile>().HasRequired(p => p.User);

 // The sql that is generated looks correct:
 alter table [dbo].[Users] add constraint [UserProfile_User] 
    foreign key ([Id]) references [dbo].[UserProfiles]([Id]) on delete cascade;

但是,在运行测试时尝试重新初始化我的模型时出现此错误; FK_dbo.UserProfiles_dbo.Users_Id 怎么了?

Test Name:  SiteRepository_Remove_TestPasses
Test FullName:  Deals.Core.Tests.Deals.Core.DataLibrary.Tests.Integration.SiteRepositoryIntegrationTests.SiteRepository_Remove_TestPasses
Test Source:    c:\Dev\Deals\Deals.Core.Tests\Deals.Core.DataLibrary.Tests\Integration\SiteRepository.Integration.Tests.cs : line 51
Test Outcome:   Failed
Test Duration:  0:00:01.4034458

Result Message: 
Initialization method Deals.Core.Tests.Deals.Core.DataLibrary.Tests.Integration.SiteRepositoryIntegrationTests.TestInitialize threw exception. System.Data.SqlClient.SqlException: System.Data.SqlClient.SqlException: 'FK_dbo.UserProfiles_dbo.Users_Id' is not a constraint.
Could not drop constraint. See previous errors..
Result StackTrace:  
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at System.Data.Entity.Migrations.DbMigrator.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements)
   at System.Data.Entity.Migrations.DbMigrator.AutoMigrate(String migrationId, XDocument sourceModel, XDocument targetModel, Boolean downgrading)
   at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
   at System.Data.Entity.MigrateDatabaseToLatestVersion`2.InitializeDatabase(TContext context)
   at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
   at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
   at Deals.Core.DataAccess.UnitOfWorkCore.ForceDatabaseInititialization() in c:\Dev\Deals\Deals.Core.DataAccess\UnitOfWorkCore.cs:line 164
   at Deals.Core.Tests.Deals.Core.DataLibrary.Tests.Integration.SiteRepositoryIntegrationTests.TestInitialize() in c:\Dev\Deals\Deals.Core.Tests\Deals.Core.DataLibrary.Tests\Integration\SiteRepository.Integration.Tests.cs:line 28

最佳答案

如果你想在删除父对象的同时删除子对象,你必须从关联的父端配置它。首先在子对象 [Required] 中创建 Foreign Key 属性,然后是以下代码。

您还应该知道,与 一对一关系 中的一对多关系 不同,默认情况下不启用级联删除,即使对于必需的关系也是如此。您必须始终明确地为一对一关系定义级联删除:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<UserProfile>()
                .HasRequired(u => u.User)
                .WithRequiredPrincipal(c => c.UserProfile)
                .WillCascadeOnDelete(true);

    modelBuilder.Entity<Survey>()
                .HasRequired(a => a.Site)
                .WithRequiredPrincipal(c => c.Survey)
                .WillCascadeOnDelete(true);
}

关于c# - 导航属性和级联删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16611096/

相关文章:

c# - 通过 DataAnnotation 强制外键列名称不起作用

c# - Entity Framework 4.1 Code First - 使用 LinqKit PredicateBuilder 时忽略包含

asp.net-mvc - 如何阻止使用 Entity Framework 在数据库中创建 View 模型

c# - 加载 XDocument 时 XML 保留回车符 (CR)

c# - 将屏幕截图捕获为图像然后使用 ffmpeg 将图像转换为视频文件的时间应该是什么?

c# - 在 C# 中使用 SSL (https) 使用 Web 服务

.net - 引入 FOREIGN KEY 约束可能会导致循环或多个级联路径 - 为什么?

c# - EF 代码优先 - 从代理获取 POCO

c# - Entity Framework 1对0或1关系配置

c# - Enumerable 和 Queryable 扩展方法的 Lambda 表达式参数