导航属性和删除时的级联
本文关键字:级联 删除 属性 导航 | 更新日期: 2023-09-27 18:14:00
我正在使用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没有得到"on delete cascade":
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
如果要在删除Parent Object的同时删除Child Object,则必须在关联的父端进行配置。首先在子对象[Required]
中创建Foreign Key
属性,然后执行以下代码:
您还应该知道,不像one-to-many relationships
在one-to-one relationships
级联删除是不启用默认,甚至不需要的关系。必须始终为一对一关系显式定义级联删除:
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);
}
这固定的
似乎我的数据库没有被删除,并在每次测试运行时重新创建…
In my DbContext
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<Context, ContextConfiguration>());
base.OnModelCreating(modelBuilder);
}
My Migration Configuration
public class ContextConfiguration : DbMigrationsConfiguration<Context>
{
public ContextConfiguration()
{
this.AutomaticMigrationsEnabled = true;
this.AutomaticMigrationDataLossAllowed = true;
}
}
在我的测试
[TestInitialize]
public override void TestInitialize()
{
// Force model updates.
using (var uow = UnitOfWorkFactory.Instance.Create<UnitOfWorkCore>(DefaultConnectionString))
{
uow.Database.Initialize(force: false);
}
// begin transaction
this.transactionScope = new TransactionScope();
this.unitOfWork = UnitOfWorkFactory.Instance.Create<UnitOfWorkCore>(DefaultConnectionString);
}
我把东西改成这个,没有问题*我把东西改成这个,没有问题*我把东西改成这个,没有问题
在我的测试
[TestInitialize]
public override void TestInitialize()
{
// Force model updates.
// I CHANGED TO THIS:
Database.SetInitializer(new DropCreateDatabaseAlways<Context>());
using (var uow = UnitOfWorkFactory.Instance.Create<UnitOfWorkCore>(DefaultConnectionString))
{
uow.Database.Initialize(force: false);
}
// begin transaction
this.transactionScope = new TransactionScope();
this.unitOfWork = UnitOfWorkFactory.Instance.Create<UnitOfWorkCore>(DefaultConnectionString);
}