我正在使用ASP.NET Core开发我的第一个API,并使用Entity Framework Core对数据建模。我无法在父对象中映射2个嵌套的类对象。
我已经阅读了一对一和一对多的内容,但是当我寻找几个一对一的映射时却一无所获,除了一些对我没有帮助的帖子。
我看过这些:
Entity Framework table with multiple optional one to one relationships
https://github.com/aspnet/EntityFrameworkCore/issues/5344
这是我的模特
Contact
类拥有2个类属性地址,并与电话联系。
然后在我的dbcontext
中,指定一对一关系。
我正在使用:
实体框架核心.NET命令行工具 2.2.3-servicing-35854
Sql服务器13.0.40001
public class Contact
{
public long Id { get; set; }
[MaxLength(40)]
[Required(ErrorMessage = "Contact name is required ")]
public string Name { get; set; }
[Required(ErrorMessage = "Company name is required ")]
public string Company { get; set; }
public string Pro`enter code here`fileImageURL { get; set; }
[Required(ErrorMessage = "Contact Emil is required ")]
public string Email { get; set; }
[Required(ErrorMessage = "Birthday is required ")]
public DateTime BirthDate { get; set; }
[Required(ErrorMessage = "Contact phone is required ")]
public ContactPhone ContactPhone { get; set; }
public Address Address { get; set; }
}
public class Address
{
public long id { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public Contact Contact { get; set; }
public long AddresssContactForeignKey { get; set; }
}
public class ContactPhone
{
public long ContactPhoneid { get; set; }
public string PersonalPhone { get; set; }
public string WorkPhone { get; set; }
public Contact Contact { get; set; }
public long ContactPhonesContactForeignKey { get; set; }
}
我的数据库上下文:
public class ContactDbContext : DbContext
{
public DbSet<Contact> Contacts { get; set; }
public DbSet<ContactPhone> ContactPhones { get; set; }
public DbSet<Address> ContactAddress { get; set; }
public ContactDbContext(DbContextOptions<ContactDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Contact>(e =>
{
e.HasOne(x => x.ContactPhone)
.WithOne(y => y.Contact)
.HasForeignKey<ContactPhone>(z =>
z.ContactPhonesContactForeignKey);
e.HasOne(x => x.Address)
.WithOne(y => y.Contact)
.HasForeignKey<Address>(z =>
z.AddresssContactForeignKey);
});
}
}
然后我应用迁移:
PM> Add-Migration Migration2
Microsoft.EntityFrameworkCore.Infrastructure [10403] 实体框架核心2.2.3-service-35854使用提供程序'Microsoft.EntityFrameworkCore.SqlServer'初始化了'ContactDbContext',选项为:无 脚手架操作可能会导致数据丢失。请检查迁移的准确性。 要撤消此操作,请使用Remove-Migration。
似乎没有错误,然后我更新数据库
PM> update-database Microsoft.EntityFrameworkCore.Infrastructure[10403]
Entity Framework Core 2.2.3-servicing-35854 initialized 'ContactDbContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (29ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT OBJECT_ID(N'[__EFMigrationsHistory]'); Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT OBJECT_ID(N'[__EFMigrationsHistory]'); Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (28ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT [MigrationId], [ProductVersion]
FROM [__EFMigrationsHistory]
ORDER BY [MigrationId]; Microsoft.EntityFrameworkCore.Migrations[20402]
Applying migration '20190323155442_Migration2'. Applying migration '20190323155442_Migration2'. Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (42ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
ALTER TABLE [ContactPhones] DROP CONSTRAINT [FK_ContactPhones_Contacts_ContactForeignKey]; Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (40ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
DROP INDEX [IX_ContactPhones_ContactForeignKey] ON [ContactPhones]; Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (385ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
DECLARE @var0 sysname;
SELECT @var0 = [d].[name]
FROM [sys].[default_constraints] [d]
INNER JOIN [sys].[columns] [c] ON [d].[parent_column_id] = [c].[column_id] AND [d].[parent_object_id] = [c].[object_id]
WHERE ([d].[parent_object_id] = OBJECT_ID(N'[Contacts]') AND [c].[name] = N'Address');
IF @var0 IS NOT NULL EXEC(N'ALTER TABLE [Contacts] DROP CONSTRAINT [' + @var0 + '];');
ALTER TABLE [Contacts] DROP COLUMN [Address]; Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (17ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
DECLARE @var1 sysname;
SELECT @var1 = [d].[name]
FROM [sys].[default_constraints] [d]
INNER JOIN [sys].[columns] [c] ON [d].[parent_column_id] = [c].[column_id] AND [d].[parent_object_id] = [c].[object_id]
WHERE ([d].[parent_object_id] = OBJECT_ID(N'[ContactPhones]') AND [c].[name] = N'ContactForeignKey');
IF @var1 IS NOT NULL EXEC(N'ALTER TABLE [ContactPhones] DROP CONSTRAINT [' + @var1 + '];');
ALTER TABLE [ContactPhones] DROP COLUMN [ContactForeignKey]; fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
Failed executing DbCommand (51ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
DECLARE @var2 sysname;
SELECT @var2 = [d].[name]
FROM [sys].[default_constraints] [d]
INNER JOIN [sys].[columns] [c] ON [d].[parent_column_id] = [c].[column_id] AND [d].[parent_object_id] = [c].[object_id]
WHERE ([d].[parent_object_id] = OBJECT_ID(N'[Contacts]') AND [c].[name] = N'Id');
IF @var2 IS NOT NULL EXEC(N'ALTER TABLE [Contacts] DROP CONSTRAINT [' + @var2 + '];');
ALTER TABLE [Contacts] ALTER COLUMN [Id] bigint NOT NULL; System.Data.SqlClient.SqlException (0x80131904): The object 'PK_Contacts' is dependent on column 'Id'. ALTER TABLE ALTER COLUMN Id failed because one or more objects access this column. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConnection.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, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite, String methodName) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues) ClientConnectionId:7bf3ba67-b8dc-4d76-a11b-c9b5ef584fad Error Number:5074,State:1,Class:16 Failed executing DbCommand (51ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] DECLARE @var2 sysname; SELECT @var2 = [d].[name] FROM [sys].[default_constraints] [d] INNER JOIN [sys].[columns] [c] ON [d].[parent_column_id] = [c].[column_id] AND [d].[parent_object_id] = [c].[object_id] WHERE ([d].[parent_object_id] = OBJECT_ID(N'[Contacts]') AND [c].[name] = N'Id'); IF @var2 IS NOT NULL EXEC(N'ALTER TABLE [Contacts] DROP CONSTRAINT [' + @var2 + '];'); ALTER TABLE [Contacts] ALTER COLUMN [Id] bigint NOT NULL; System.Data.SqlClient.SqlException (0x80131904): The object 'PK_Contacts' is dependent on column 'Id'. ALTER TABLE ALTER COLUMN Id failed because one or more objects access this column. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConnection.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, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite, String methodName) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues) at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues) at Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues) at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection) at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration) at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_1.<.ctor>b__0() at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action) ClientConnectionId:7bf3ba67-b8dc-4d76-a11b-c9b5ef584fad Error Number:5074,State:1,Class:16 The object 'PK_Contacts' is dependent on column 'Id'. ALTER TABLE ALTER COLUMN Id failed because one or more objects access this column.
这就是由此产生的迁移
public partial class Migration2 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_ContactPhones_Contacts_ContactForeignKey",
table: "ContactPhones");
migrationBuilder.DropIndex(
name: "IX_ContactPhones_ContactForeignKey",
table: "ContactPhones");
migrationBuilder.DropColumn(
name: "Address",
table: "Contacts");
migrationBuilder.DropColumn(
name: "ContactForeignKey",
table: "ContactPhones");
migrationBuilder.AlterColumn<long>(
name: "Id",
table: "Contacts",
nullable: false,
oldClrType: typeof(int))
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn)
.OldAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
migrationBuilder.AlterColumn<long>(
name: "ContactPhoneid",
table: "ContactPhones",
nullable: false,
oldClrType: typeof(int))
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn)
.OldAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
migrationBuilder.AddColumn<long>(
name: "ContactPhonesContactForeignKey",
table: "ContactPhones",
nullable: false,
defaultValue: 0L);
migrationBuilder.CreateTable(
name: "ContactAddress",
columns: table => new
{
id = table.Column<long>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy",
SqlServerValueGenerationStrategy.IdentityColumn),
AddressLine1 = table.Column<string>(nullable: true),
AddressLine2 = table.Column<string>(nullable: true),
City = table.Column<string>(nullable: true),
State = table.Column<string>(nullable: true),
AddresssContactForeignKey = table.Column<long>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ContactAddress", x => x.id);
table.ForeignKey(
name: "FK_ContactAddress_Contacts_AddresssContactForeignKey",
column: x => x.AddresssContactForeignKey,
principalTable: "Contacts",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_ContactPhones_ContactPhonesContactForeignKey",
table: "ContactPhones",
column: "ContactPhonesContactForeignKey",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_ContactAddress_AddresssContactForeignKey",
table: "ContactAddress",
column: "AddresssContactForeignKey",
unique: true);
migrationBuilder.AddForeignKey(
name: "FK_ContactPhones_Contacts_ContactPhonesContactForeignKey",
table: "ContactPhones",
column: "ContactPhonesContactForeignKey",
principalTable: "Contacts",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_ContactPhones_Contacts_ContactPhonesContactForeignKey",
table: "ContactPhones");
migrationBuilder.DropTable(
name: "ContactAddress");
migrationBuilder.DropIndex(
name: "IX_ContactPhones_ContactPhonesContactForeignKey",
table: "ContactPhones");
migrationBuilder.DropColumn(
name: "ContactPhonesContactForeignKey",
table: "ContactPhones");
migrationBuilder.AlterColumn<int>(
name: "Id",
table: "Contacts",
nullable: false,
oldClrType: typeof(long))
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn)
.OldAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
migrationBuilder.AddColumn<string>(
name: "Address",
table: "Contacts",
nullable: false,
defaultValue: "");
migrationBuilder.AlterColumn<int>(
name: "ContactPhoneid",
table: "ContactPhones",
nullable: false,
oldClrType: typeof(long))
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn)
.OldAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
migrationBuilder.AddColumn<int>(
name: "ContactForeignKey",
table: "ContactPhones",
nullable: false,
defaultValue: 0);
migrationBuilder.CreateIndex(
name: "IX_ContactPhones_ContactForeignKey",
table: "ContactPhones",
column: "ContactForeignKey",
unique: true);
migrationBuilder.AddForeignKey(
name: "FK_ContactPhones_Contacts_ContactForeignKey",
table: "ContactPhones",
column: "ContactForeignKey",
principalTable: "Contacts",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
}
最后,控制台抛出此错误:
错误号:5074,状态:1,类:16
对象“ PK_Contacts”取决于列“ Id”。
ALTER TABLE ALTER COLUMN ID失败,因为一个或多个对象访问此列。
我希望映射为1:1
更新
我发现了问题。 我以前将所有实体ID都设为 int ,然后将其更改为 long 我使用编写的代码启动了一个新项目,并通过第一次迁移启动了一个新数据库,并且该数据库正常工作 感谢所有非常乐意帮助我完成工作的人!
答案 0 :(得分:0)
更新
我发现了问题。我以前将所有实体ID都设置为 int ,然后将它们更改为 long 。我用书面代码启动了一个新项目,并通过第一次迁移并启动了一个新数据库,感谢所有能帮助我完成工作的人!