Can't map model with a couple of one to one relations with Entity Framework CoreEntity Framework table with multiple optional one to one relationshipsHow can I get Id of inserted entity in Entity framework?Fastest Way of Inserting in Entity FrameworkEntity Framework 5 Updating a RecordCommand timeout SQL Server 2014 + Entity FrameworkModelling folder structure in Entity Framework CoreEntity Framework migration errorWhat is the permission needed for a SQL Server login to change a tables name?EF Core “Cannot insert explicit value for identity column” although IDENTIY_INSERT is set to ONEF Core migration fails, table already createdHow to create two one-to-one relations with same entity in Entity Framework Core

A♭ major 9th chord in Bach is unexpectedly dissonant/jazzy

How to get the decimal part of a number in apex

shebang or not shebang

How to make a kid's bike easier to pedal

What is more safe for browsing the web: PC or smartphone?

What chord could the notes 'F A♭ E♭' form?

Do the Zhentarim fire members for killing fellow members?

Does this website provide consistent translation into Wookiee?

Concatenate all values of the same XML element using XPath/XQuery

Why can’t you see at the start of the Big Bang?

What’s the interaction between darkvision and the Eagle Aspect of the beast, if you have Darkvision past 100 feet?

How do I minimise waste on a flight?

Why always 4...dxc6 and not 4...bxc6 in the Ruy Lopez Exchange?

How does "politician" work as a job/career?

What detail can Hubble see on Mars?

Appropriate age to involve kids in life changing decisions

Crime rates in a post-scarcity economy

If quadruped mammals evolve to become bipedal will their breast or nipple change position?

Where do 5 or more U.S. counties meet in a single point?

What does the copyright in a dissertation protect exactly?

Was there a dinosaur-counter in the original Jurassic Park movie?

What is the Ancient One's mistake?

Translation of "invincible independence"

Is there a reason why Turkey took the Balkan territories of the Ottoman Empire, instead of Greece or another of the Balkan states?



Can't map model with a couple of one to one relations with Entity Framework Core


Entity Framework table with multiple optional one to one relationshipsHow can I get Id of inserted entity in Entity framework?Fastest Way of Inserting in Entity FrameworkEntity Framework 5 Updating a RecordCommand timeout SQL Server 2014 + Entity FrameworkModelling folder structure in Entity Framework CoreEntity Framework migration errorWhat is the permission needed for a SQL Server login to change a tables name?EF Core “Cannot insert explicit value for identity column” although IDENTIY_INSERT is set to ONEF Core migration fails, table already createdHow to create two one-to-one relations with same entity in Entity Framework Core






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I'm developing my first API with ASP.NET Core, and using Entity Framework Core to model my data. I can't map 2 nested class objects within the parent one.



I've read about one to one, and one to many, but I get nothing when I look for several one to one mappings except some posts that didn't help me.



I've seen these:



Entity Framework table with multiple optional one to one relationships



https://github.com/aspnet/EntityFrameworkCore/issues/5344



This is my model



The Contact class owns 2 class properties address, and contact phone.
Then in my dbcontext, I specify both one to one relations.
Im using :



Entity Framework Core .NET Command-line Tools
2.2.3-servicing-35854



Sql server 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;



My DB context:



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);
);




Then i apply the migration :



PM> Add-Migration Migration2


Microsoft.EntityFrameworkCore.Infrastructure[10403]
Entity Framework Core 2.2.3-servicing-35854 initialized 'ContactDbContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None
An operation was scaffolded that may result in the loss of data. Please review the migration for accuracy.
To undo this action, use Remove-Migration.



Seems there are no errors, then I update the database



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.


And this is the resulting Migration



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);




Finally the console throws this :




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.




I expect the mapping to be 1:1




UPDATE




Ive found the problem.
I used to have all my entities Ids beint int, then i changed them to long
I started a new project with the written code and started a new database with a first migration and it worked
THanks to everyone that was so nice to help me through it !!










share|improve this question
























  • Hi Maximo Gonzalez. Would you mind sending your migrations code and how you setup your DbContext? I've copied your code as-is and managed to run everything successfully. I could run the migrations, save an object and load an object. I had to add the EF Proxies (or you can at the very least invoke Include on those navigation properties of Contact when you perform a query) to see that it loads Address and ContactPhone (which it did just fine).

    – Dandré
    Mar 23 at 8:26











  • What EF Core version are you using and what database type? Because with the latest official EF Core 2.2.3 and SqlServer the generated migration from the sample model runs just fine.

    – Ivan Stoev
    Mar 23 at 11:40











  • Hi @Dandré ive added the migrations code, the mi db context setup was already in the post ! I have no problem when i run the migration but when i update the database. IvanStoev Ive added the ef version and database version and type i use. They are the latest. Thanks both for answering

    – Maximo Gonzalez
    Mar 23 at 16:08











  • @MaximoGonzalez Your use case seems like a good fit for EF Core Owned Entities: docs.microsoft.com/en-us/ef/core/modeling/owned-entities

    – Marko Papic
    Mar 23 at 16:24











  • @MaximoGonzalez I would recommend adding your update as an answer to this post since you have solved the issue.

    – Priyank Panchal
    Mar 23 at 16:59

















1















I'm developing my first API with ASP.NET Core, and using Entity Framework Core to model my data. I can't map 2 nested class objects within the parent one.



I've read about one to one, and one to many, but I get nothing when I look for several one to one mappings except some posts that didn't help me.



I've seen these:



Entity Framework table with multiple optional one to one relationships



https://github.com/aspnet/EntityFrameworkCore/issues/5344



This is my model



The Contact class owns 2 class properties address, and contact phone.
Then in my dbcontext, I specify both one to one relations.
Im using :



Entity Framework Core .NET Command-line Tools
2.2.3-servicing-35854



Sql server 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;



My DB context:



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);
);




Then i apply the migration :



PM> Add-Migration Migration2


Microsoft.EntityFrameworkCore.Infrastructure[10403]
Entity Framework Core 2.2.3-servicing-35854 initialized 'ContactDbContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None
An operation was scaffolded that may result in the loss of data. Please review the migration for accuracy.
To undo this action, use Remove-Migration.



Seems there are no errors, then I update the database



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.


And this is the resulting Migration



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);




Finally the console throws this :




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.




I expect the mapping to be 1:1




UPDATE




Ive found the problem.
I used to have all my entities Ids beint int, then i changed them to long
I started a new project with the written code and started a new database with a first migration and it worked
THanks to everyone that was so nice to help me through it !!










share|improve this question
























  • Hi Maximo Gonzalez. Would you mind sending your migrations code and how you setup your DbContext? I've copied your code as-is and managed to run everything successfully. I could run the migrations, save an object and load an object. I had to add the EF Proxies (or you can at the very least invoke Include on those navigation properties of Contact when you perform a query) to see that it loads Address and ContactPhone (which it did just fine).

    – Dandré
    Mar 23 at 8:26











  • What EF Core version are you using and what database type? Because with the latest official EF Core 2.2.3 and SqlServer the generated migration from the sample model runs just fine.

    – Ivan Stoev
    Mar 23 at 11:40











  • Hi @Dandré ive added the migrations code, the mi db context setup was already in the post ! I have no problem when i run the migration but when i update the database. IvanStoev Ive added the ef version and database version and type i use. They are the latest. Thanks both for answering

    – Maximo Gonzalez
    Mar 23 at 16:08











  • @MaximoGonzalez Your use case seems like a good fit for EF Core Owned Entities: docs.microsoft.com/en-us/ef/core/modeling/owned-entities

    – Marko Papic
    Mar 23 at 16:24











  • @MaximoGonzalez I would recommend adding your update as an answer to this post since you have solved the issue.

    – Priyank Panchal
    Mar 23 at 16:59













1












1








1








I'm developing my first API with ASP.NET Core, and using Entity Framework Core to model my data. I can't map 2 nested class objects within the parent one.



I've read about one to one, and one to many, but I get nothing when I look for several one to one mappings except some posts that didn't help me.



I've seen these:



Entity Framework table with multiple optional one to one relationships



https://github.com/aspnet/EntityFrameworkCore/issues/5344



This is my model



The Contact class owns 2 class properties address, and contact phone.
Then in my dbcontext, I specify both one to one relations.
Im using :



Entity Framework Core .NET Command-line Tools
2.2.3-servicing-35854



Sql server 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;



My DB context:



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);
);




Then i apply the migration :



PM> Add-Migration Migration2


Microsoft.EntityFrameworkCore.Infrastructure[10403]
Entity Framework Core 2.2.3-servicing-35854 initialized 'ContactDbContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None
An operation was scaffolded that may result in the loss of data. Please review the migration for accuracy.
To undo this action, use Remove-Migration.



Seems there are no errors, then I update the database



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.


And this is the resulting Migration



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);




Finally the console throws this :




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.




I expect the mapping to be 1:1




UPDATE




Ive found the problem.
I used to have all my entities Ids beint int, then i changed them to long
I started a new project with the written code and started a new database with a first migration and it worked
THanks to everyone that was so nice to help me through it !!










share|improve this question
















I'm developing my first API with ASP.NET Core, and using Entity Framework Core to model my data. I can't map 2 nested class objects within the parent one.



I've read about one to one, and one to many, but I get nothing when I look for several one to one mappings except some posts that didn't help me.



I've seen these:



Entity Framework table with multiple optional one to one relationships



https://github.com/aspnet/EntityFrameworkCore/issues/5344



This is my model



The Contact class owns 2 class properties address, and contact phone.
Then in my dbcontext, I specify both one to one relations.
Im using :



Entity Framework Core .NET Command-line Tools
2.2.3-servicing-35854



Sql server 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;



My DB context:



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);
);




Then i apply the migration :



PM> Add-Migration Migration2


Microsoft.EntityFrameworkCore.Infrastructure[10403]
Entity Framework Core 2.2.3-servicing-35854 initialized 'ContactDbContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None
An operation was scaffolded that may result in the loss of data. Please review the migration for accuracy.
To undo this action, use Remove-Migration.



Seems there are no errors, then I update the database



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.


And this is the resulting Migration



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);




Finally the console throws this :




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.




I expect the mapping to be 1:1




UPDATE




Ive found the problem.
I used to have all my entities Ids beint int, then i changed them to long
I started a new project with the written code and started a new database with a first migration and it worked
THanks to everyone that was so nice to help me through it !!







c# entity-framework-core






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 23 at 16:58







Maximo Gonzalez

















asked Mar 23 at 6:14









Maximo GonzalezMaximo Gonzalez

63




63












  • Hi Maximo Gonzalez. Would you mind sending your migrations code and how you setup your DbContext? I've copied your code as-is and managed to run everything successfully. I could run the migrations, save an object and load an object. I had to add the EF Proxies (or you can at the very least invoke Include on those navigation properties of Contact when you perform a query) to see that it loads Address and ContactPhone (which it did just fine).

    – Dandré
    Mar 23 at 8:26











  • What EF Core version are you using and what database type? Because with the latest official EF Core 2.2.3 and SqlServer the generated migration from the sample model runs just fine.

    – Ivan Stoev
    Mar 23 at 11:40











  • Hi @Dandré ive added the migrations code, the mi db context setup was already in the post ! I have no problem when i run the migration but when i update the database. IvanStoev Ive added the ef version and database version and type i use. They are the latest. Thanks both for answering

    – Maximo Gonzalez
    Mar 23 at 16:08











  • @MaximoGonzalez Your use case seems like a good fit for EF Core Owned Entities: docs.microsoft.com/en-us/ef/core/modeling/owned-entities

    – Marko Papic
    Mar 23 at 16:24











  • @MaximoGonzalez I would recommend adding your update as an answer to this post since you have solved the issue.

    – Priyank Panchal
    Mar 23 at 16:59

















  • Hi Maximo Gonzalez. Would you mind sending your migrations code and how you setup your DbContext? I've copied your code as-is and managed to run everything successfully. I could run the migrations, save an object and load an object. I had to add the EF Proxies (or you can at the very least invoke Include on those navigation properties of Contact when you perform a query) to see that it loads Address and ContactPhone (which it did just fine).

    – Dandré
    Mar 23 at 8:26











  • What EF Core version are you using and what database type? Because with the latest official EF Core 2.2.3 and SqlServer the generated migration from the sample model runs just fine.

    – Ivan Stoev
    Mar 23 at 11:40











  • Hi @Dandré ive added the migrations code, the mi db context setup was already in the post ! I have no problem when i run the migration but when i update the database. IvanStoev Ive added the ef version and database version and type i use. They are the latest. Thanks both for answering

    – Maximo Gonzalez
    Mar 23 at 16:08











  • @MaximoGonzalez Your use case seems like a good fit for EF Core Owned Entities: docs.microsoft.com/en-us/ef/core/modeling/owned-entities

    – Marko Papic
    Mar 23 at 16:24











  • @MaximoGonzalez I would recommend adding your update as an answer to this post since you have solved the issue.

    – Priyank Panchal
    Mar 23 at 16:59
















Hi Maximo Gonzalez. Would you mind sending your migrations code and how you setup your DbContext? I've copied your code as-is and managed to run everything successfully. I could run the migrations, save an object and load an object. I had to add the EF Proxies (or you can at the very least invoke Include on those navigation properties of Contact when you perform a query) to see that it loads Address and ContactPhone (which it did just fine).

– Dandré
Mar 23 at 8:26





Hi Maximo Gonzalez. Would you mind sending your migrations code and how you setup your DbContext? I've copied your code as-is and managed to run everything successfully. I could run the migrations, save an object and load an object. I had to add the EF Proxies (or you can at the very least invoke Include on those navigation properties of Contact when you perform a query) to see that it loads Address and ContactPhone (which it did just fine).

– Dandré
Mar 23 at 8:26













What EF Core version are you using and what database type? Because with the latest official EF Core 2.2.3 and SqlServer the generated migration from the sample model runs just fine.

– Ivan Stoev
Mar 23 at 11:40





What EF Core version are you using and what database type? Because with the latest official EF Core 2.2.3 and SqlServer the generated migration from the sample model runs just fine.

– Ivan Stoev
Mar 23 at 11:40













Hi @Dandré ive added the migrations code, the mi db context setup was already in the post ! I have no problem when i run the migration but when i update the database. IvanStoev Ive added the ef version and database version and type i use. They are the latest. Thanks both for answering

– Maximo Gonzalez
Mar 23 at 16:08





Hi @Dandré ive added the migrations code, the mi db context setup was already in the post ! I have no problem when i run the migration but when i update the database. IvanStoev Ive added the ef version and database version and type i use. They are the latest. Thanks both for answering

– Maximo Gonzalez
Mar 23 at 16:08













@MaximoGonzalez Your use case seems like a good fit for EF Core Owned Entities: docs.microsoft.com/en-us/ef/core/modeling/owned-entities

– Marko Papic
Mar 23 at 16:24





@MaximoGonzalez Your use case seems like a good fit for EF Core Owned Entities: docs.microsoft.com/en-us/ef/core/modeling/owned-entities

– Marko Papic
Mar 23 at 16:24













@MaximoGonzalez I would recommend adding your update as an answer to this post since you have solved the issue.

– Priyank Panchal
Mar 23 at 16:59





@MaximoGonzalez I would recommend adding your update as an answer to this post since you have solved the issue.

– Priyank Panchal
Mar 23 at 16:59












1 Answer
1






active

oldest

votes


















0














UPDATE



Ive found the problem. I used to have all my entities Ids beint int, then i changed them to long I started a new project with the written code and started a new database with a first migration and it worked Thanks to everyone that was so nice to help me through it !!






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55311139%2fcant-map-model-with-a-couple-of-one-to-one-relations-with-entity-framework-core%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    UPDATE



    Ive found the problem. I used to have all my entities Ids beint int, then i changed them to long I started a new project with the written code and started a new database with a first migration and it worked Thanks to everyone that was so nice to help me through it !!






    share|improve this answer



























      0














      UPDATE



      Ive found the problem. I used to have all my entities Ids beint int, then i changed them to long I started a new project with the written code and started a new database with a first migration and it worked Thanks to everyone that was so nice to help me through it !!






      share|improve this answer

























        0












        0








        0







        UPDATE



        Ive found the problem. I used to have all my entities Ids beint int, then i changed them to long I started a new project with the written code and started a new database with a first migration and it worked Thanks to everyone that was so nice to help me through it !!






        share|improve this answer













        UPDATE



        Ive found the problem. I used to have all my entities Ids beint int, then i changed them to long I started a new project with the written code and started a new database with a first migration and it worked Thanks to everyone that was so nice to help me through it !!







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 23 at 17:46









        Maximo GonzalezMaximo Gonzalez

        63




        63





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55311139%2fcant-map-model-with-a-couple-of-one-to-one-relations-with-entity-framework-core%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현