Entity Framework Core: FK with Different DataType than PK










2















Runtime: netcoreapp2.0



ASP.Net Core: 2.0.1



EF Core: 2.0.1



Microsoft.EntityFrameworkCore.SqlServer: 2.0.1



So, I'm working on an old database that is being used by lots of services and the original creators defined the PK of one table as short and a FK to that table as an int. Is it at all possible for me to handle this case?



Note: it is not feasible to change the column type at this time.



Consider the two classes:



public class Database 
public short DatabaseId get; set;
public Database get; set;


public class Client
public int ClientId get; set;
public int DatabaseId get; set;
public Database Database get; set;



My first attempt:



public int DatabaseId get; set; 
[ForeignKey("DatabaseId")] public Database Database get; set;


throws



System.InvalidOperationException: The relationship from 'Client.Database' to 'Database.Client' with foreign key properties 'DatabaseId' : int cannot target the primary key 'DatabaseId' : short because it is not compatible. Configure a principal key or a set of compatible foreign key properties for this relationship.


Using the fluent API now:



modelBuilder.Entity<Client>(table => 
table.HasOne(p => p.Database)
.WithOne(i => i.Client)
.HasForeignKey<Client>(c => c.DatabaseId)
.HasPrincipalKey<Database>(d => d.DatabaseID);
);


Attempting to define a shadow property failed



modelBuilder.Entity<Client>(table => 
table.Property<int>("DatabaseId");

table.HasOne(p => p.Database)
.WithOne(i => i.Client)
.HasForeignKey("DatabaseId")
.HasPrincipalKey<Database>(d => d.DatabaseId);
);


throws



System.InvalidOperationException: You are configuring a relationship between 'Client' and 'Database' but have specified a foreign key on 'DatabaseId'. The foreign key must be defined on a type that is part of the relationship.


Okay, so no shadow properties this time:



modelBuilder.Entity<Client>(table => 

table.HasOne(p => p.Database)
.WithOne(i => i.Client)
.HasForeignKey<Client>(c => c.DatabaseId)
.HasPrincipalKey<Database>(d => d.SQLDatabaseID);
);


throws



System.InvalidOperationException: The types of the properties specified for the foreign key 'DatabaseId' on entity type 'Client' do not match the types of the properties in the principal key 'DatabaseID' on entity type 'Database'.


So, then I tried just changing the entity type and maybe EF will be able to map int to int16.



public class Client 
public int ClientId get; set;
public short DatabaseId get; set; // <-- now a short
public Database Database get; set;



throws



System.InvalidOperationException: An exception occurred while reading a database value for property 'Client.DatabaseId'. The expected type was 'System.Int16' but the actual value was of type 'System.Int32'. ---> System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.Int16'.


I'm starting to get the feeling this is not possible.










share|improve this question






















  • So... what would happen if you had a row with id short.MaxValue + 1? How would EF map that to short? How would you store the value on the database? Can you change the database?

    – Camilo Terevinto
    Feb 26 '18 at 23:26












  • Damn thats a dousy not sure what they where thinking when making an Id a short. But If its impossible to change the schema you can convert your Identifiers to ToString() while executing linq queries(dirty un-maintainable fix). You can also explicitly convert by casting ex Convert.ToInt16(int.MaxValue);

    – Mohamoud Mohamed
    Feb 26 '18 at 23:29











  • I am still trying to figure why in gods name you would use a SHORT

    – mvermef
    Feb 27 '18 at 6:12











  • The problem isn't just executing simple queries which would be fine...The problem occurs when trying to follow the navigation properties e.g. _databases.Include(d => d.Client) EF can't follow the navigation property

    – jaredcnance
    Feb 27 '18 at 18:09











  • I have duplicated your attempt reference my comment on the answer below...

    – mvermef
    Feb 27 '18 at 23:26















2















Runtime: netcoreapp2.0



ASP.Net Core: 2.0.1



EF Core: 2.0.1



Microsoft.EntityFrameworkCore.SqlServer: 2.0.1



So, I'm working on an old database that is being used by lots of services and the original creators defined the PK of one table as short and a FK to that table as an int. Is it at all possible for me to handle this case?



Note: it is not feasible to change the column type at this time.



Consider the two classes:



public class Database 
public short DatabaseId get; set;
public Database get; set;


public class Client
public int ClientId get; set;
public int DatabaseId get; set;
public Database Database get; set;



My first attempt:



public int DatabaseId get; set; 
[ForeignKey("DatabaseId")] public Database Database get; set;


throws



System.InvalidOperationException: The relationship from 'Client.Database' to 'Database.Client' with foreign key properties 'DatabaseId' : int cannot target the primary key 'DatabaseId' : short because it is not compatible. Configure a principal key or a set of compatible foreign key properties for this relationship.


Using the fluent API now:



modelBuilder.Entity<Client>(table => 
table.HasOne(p => p.Database)
.WithOne(i => i.Client)
.HasForeignKey<Client>(c => c.DatabaseId)
.HasPrincipalKey<Database>(d => d.DatabaseID);
);


Attempting to define a shadow property failed



modelBuilder.Entity<Client>(table => 
table.Property<int>("DatabaseId");

table.HasOne(p => p.Database)
.WithOne(i => i.Client)
.HasForeignKey("DatabaseId")
.HasPrincipalKey<Database>(d => d.DatabaseId);
);


throws



System.InvalidOperationException: You are configuring a relationship between 'Client' and 'Database' but have specified a foreign key on 'DatabaseId'. The foreign key must be defined on a type that is part of the relationship.


Okay, so no shadow properties this time:



modelBuilder.Entity<Client>(table => 

table.HasOne(p => p.Database)
.WithOne(i => i.Client)
.HasForeignKey<Client>(c => c.DatabaseId)
.HasPrincipalKey<Database>(d => d.SQLDatabaseID);
);


throws



System.InvalidOperationException: The types of the properties specified for the foreign key 'DatabaseId' on entity type 'Client' do not match the types of the properties in the principal key 'DatabaseID' on entity type 'Database'.


So, then I tried just changing the entity type and maybe EF will be able to map int to int16.



public class Client 
public int ClientId get; set;
public short DatabaseId get; set; // <-- now a short
public Database Database get; set;



throws



System.InvalidOperationException: An exception occurred while reading a database value for property 'Client.DatabaseId'. The expected type was 'System.Int16' but the actual value was of type 'System.Int32'. ---> System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.Int16'.


I'm starting to get the feeling this is not possible.










share|improve this question






















  • So... what would happen if you had a row with id short.MaxValue + 1? How would EF map that to short? How would you store the value on the database? Can you change the database?

    – Camilo Terevinto
    Feb 26 '18 at 23:26












  • Damn thats a dousy not sure what they where thinking when making an Id a short. But If its impossible to change the schema you can convert your Identifiers to ToString() while executing linq queries(dirty un-maintainable fix). You can also explicitly convert by casting ex Convert.ToInt16(int.MaxValue);

    – Mohamoud Mohamed
    Feb 26 '18 at 23:29











  • I am still trying to figure why in gods name you would use a SHORT

    – mvermef
    Feb 27 '18 at 6:12











  • The problem isn't just executing simple queries which would be fine...The problem occurs when trying to follow the navigation properties e.g. _databases.Include(d => d.Client) EF can't follow the navigation property

    – jaredcnance
    Feb 27 '18 at 18:09











  • I have duplicated your attempt reference my comment on the answer below...

    – mvermef
    Feb 27 '18 at 23:26













2












2








2


0






Runtime: netcoreapp2.0



ASP.Net Core: 2.0.1



EF Core: 2.0.1



Microsoft.EntityFrameworkCore.SqlServer: 2.0.1



So, I'm working on an old database that is being used by lots of services and the original creators defined the PK of one table as short and a FK to that table as an int. Is it at all possible for me to handle this case?



Note: it is not feasible to change the column type at this time.



Consider the two classes:



public class Database 
public short DatabaseId get; set;
public Database get; set;


public class Client
public int ClientId get; set;
public int DatabaseId get; set;
public Database Database get; set;



My first attempt:



public int DatabaseId get; set; 
[ForeignKey("DatabaseId")] public Database Database get; set;


throws



System.InvalidOperationException: The relationship from 'Client.Database' to 'Database.Client' with foreign key properties 'DatabaseId' : int cannot target the primary key 'DatabaseId' : short because it is not compatible. Configure a principal key or a set of compatible foreign key properties for this relationship.


Using the fluent API now:



modelBuilder.Entity<Client>(table => 
table.HasOne(p => p.Database)
.WithOne(i => i.Client)
.HasForeignKey<Client>(c => c.DatabaseId)
.HasPrincipalKey<Database>(d => d.DatabaseID);
);


Attempting to define a shadow property failed



modelBuilder.Entity<Client>(table => 
table.Property<int>("DatabaseId");

table.HasOne(p => p.Database)
.WithOne(i => i.Client)
.HasForeignKey("DatabaseId")
.HasPrincipalKey<Database>(d => d.DatabaseId);
);


throws



System.InvalidOperationException: You are configuring a relationship between 'Client' and 'Database' but have specified a foreign key on 'DatabaseId'. The foreign key must be defined on a type that is part of the relationship.


Okay, so no shadow properties this time:



modelBuilder.Entity<Client>(table => 

table.HasOne(p => p.Database)
.WithOne(i => i.Client)
.HasForeignKey<Client>(c => c.DatabaseId)
.HasPrincipalKey<Database>(d => d.SQLDatabaseID);
);


throws



System.InvalidOperationException: The types of the properties specified for the foreign key 'DatabaseId' on entity type 'Client' do not match the types of the properties in the principal key 'DatabaseID' on entity type 'Database'.


So, then I tried just changing the entity type and maybe EF will be able to map int to int16.



public class Client 
public int ClientId get; set;
public short DatabaseId get; set; // <-- now a short
public Database Database get; set;



throws



System.InvalidOperationException: An exception occurred while reading a database value for property 'Client.DatabaseId'. The expected type was 'System.Int16' but the actual value was of type 'System.Int32'. ---> System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.Int16'.


I'm starting to get the feeling this is not possible.










share|improve this question














Runtime: netcoreapp2.0



ASP.Net Core: 2.0.1



EF Core: 2.0.1



Microsoft.EntityFrameworkCore.SqlServer: 2.0.1



So, I'm working on an old database that is being used by lots of services and the original creators defined the PK of one table as short and a FK to that table as an int. Is it at all possible for me to handle this case?



Note: it is not feasible to change the column type at this time.



Consider the two classes:



public class Database 
public short DatabaseId get; set;
public Database get; set;


public class Client
public int ClientId get; set;
public int DatabaseId get; set;
public Database Database get; set;



My first attempt:



public int DatabaseId get; set; 
[ForeignKey("DatabaseId")] public Database Database get; set;


throws



System.InvalidOperationException: The relationship from 'Client.Database' to 'Database.Client' with foreign key properties 'DatabaseId' : int cannot target the primary key 'DatabaseId' : short because it is not compatible. Configure a principal key or a set of compatible foreign key properties for this relationship.


Using the fluent API now:



modelBuilder.Entity<Client>(table => 
table.HasOne(p => p.Database)
.WithOne(i => i.Client)
.HasForeignKey<Client>(c => c.DatabaseId)
.HasPrincipalKey<Database>(d => d.DatabaseID);
);


Attempting to define a shadow property failed



modelBuilder.Entity<Client>(table => 
table.Property<int>("DatabaseId");

table.HasOne(p => p.Database)
.WithOne(i => i.Client)
.HasForeignKey("DatabaseId")
.HasPrincipalKey<Database>(d => d.DatabaseId);
);


throws



System.InvalidOperationException: You are configuring a relationship between 'Client' and 'Database' but have specified a foreign key on 'DatabaseId'. The foreign key must be defined on a type that is part of the relationship.


Okay, so no shadow properties this time:



modelBuilder.Entity<Client>(table => 

table.HasOne(p => p.Database)
.WithOne(i => i.Client)
.HasForeignKey<Client>(c => c.DatabaseId)
.HasPrincipalKey<Database>(d => d.SQLDatabaseID);
);


throws



System.InvalidOperationException: The types of the properties specified for the foreign key 'DatabaseId' on entity type 'Client' do not match the types of the properties in the principal key 'DatabaseID' on entity type 'Database'.


So, then I tried just changing the entity type and maybe EF will be able to map int to int16.



public class Client 
public int ClientId get; set;
public short DatabaseId get; set; // <-- now a short
public Database Database get; set;



throws



System.InvalidOperationException: An exception occurred while reading a database value for property 'Client.DatabaseId'. The expected type was 'System.Int16' but the actual value was of type 'System.Int32'. ---> System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.Int16'.


I'm starting to get the feeling this is not possible.







c# entity-framework-core






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Feb 26 '18 at 23:13









jaredcnancejaredcnance

161112




161112












  • So... what would happen if you had a row with id short.MaxValue + 1? How would EF map that to short? How would you store the value on the database? Can you change the database?

    – Camilo Terevinto
    Feb 26 '18 at 23:26












  • Damn thats a dousy not sure what they where thinking when making an Id a short. But If its impossible to change the schema you can convert your Identifiers to ToString() while executing linq queries(dirty un-maintainable fix). You can also explicitly convert by casting ex Convert.ToInt16(int.MaxValue);

    – Mohamoud Mohamed
    Feb 26 '18 at 23:29











  • I am still trying to figure why in gods name you would use a SHORT

    – mvermef
    Feb 27 '18 at 6:12











  • The problem isn't just executing simple queries which would be fine...The problem occurs when trying to follow the navigation properties e.g. _databases.Include(d => d.Client) EF can't follow the navigation property

    – jaredcnance
    Feb 27 '18 at 18:09











  • I have duplicated your attempt reference my comment on the answer below...

    – mvermef
    Feb 27 '18 at 23:26

















  • So... what would happen if you had a row with id short.MaxValue + 1? How would EF map that to short? How would you store the value on the database? Can you change the database?

    – Camilo Terevinto
    Feb 26 '18 at 23:26












  • Damn thats a dousy not sure what they where thinking when making an Id a short. But If its impossible to change the schema you can convert your Identifiers to ToString() while executing linq queries(dirty un-maintainable fix). You can also explicitly convert by casting ex Convert.ToInt16(int.MaxValue);

    – Mohamoud Mohamed
    Feb 26 '18 at 23:29











  • I am still trying to figure why in gods name you would use a SHORT

    – mvermef
    Feb 27 '18 at 6:12











  • The problem isn't just executing simple queries which would be fine...The problem occurs when trying to follow the navigation properties e.g. _databases.Include(d => d.Client) EF can't follow the navigation property

    – jaredcnance
    Feb 27 '18 at 18:09











  • I have duplicated your attempt reference my comment on the answer below...

    – mvermef
    Feb 27 '18 at 23:26
















So... what would happen if you had a row with id short.MaxValue + 1? How would EF map that to short? How would you store the value on the database? Can you change the database?

– Camilo Terevinto
Feb 26 '18 at 23:26






So... what would happen if you had a row with id short.MaxValue + 1? How would EF map that to short? How would you store the value on the database? Can you change the database?

– Camilo Terevinto
Feb 26 '18 at 23:26














Damn thats a dousy not sure what they where thinking when making an Id a short. But If its impossible to change the schema you can convert your Identifiers to ToString() while executing linq queries(dirty un-maintainable fix). You can also explicitly convert by casting ex Convert.ToInt16(int.MaxValue);

– Mohamoud Mohamed
Feb 26 '18 at 23:29





Damn thats a dousy not sure what they where thinking when making an Id a short. But If its impossible to change the schema you can convert your Identifiers to ToString() while executing linq queries(dirty un-maintainable fix). You can also explicitly convert by casting ex Convert.ToInt16(int.MaxValue);

– Mohamoud Mohamed
Feb 26 '18 at 23:29













I am still trying to figure why in gods name you would use a SHORT

– mvermef
Feb 27 '18 at 6:12





I am still trying to figure why in gods name you would use a SHORT

– mvermef
Feb 27 '18 at 6:12













The problem isn't just executing simple queries which would be fine...The problem occurs when trying to follow the navigation properties e.g. _databases.Include(d => d.Client) EF can't follow the navigation property

– jaredcnance
Feb 27 '18 at 18:09





The problem isn't just executing simple queries which would be fine...The problem occurs when trying to follow the navigation properties e.g. _databases.Include(d => d.Client) EF can't follow the navigation property

– jaredcnance
Feb 27 '18 at 18:09













I have duplicated your attempt reference my comment on the answer below...

– mvermef
Feb 27 '18 at 23:26





I have duplicated your attempt reference my comment on the answer below...

– mvermef
Feb 27 '18 at 23:26












2 Answers
2






active

oldest

votes


















2














In EF Core 2.1 you can use value conversions, i.e.



entityBuilder.Property(c => c.Id).HasConversion<string>(); 


where the generic string is the database type and the destination is the model type. You can read further on https://docs.microsoft.com/es-es/ef/core/modeling/value-conversions






share|improve this answer






























    1














    You can bypass error generated by entity framework by using the following code to define your foreign key



    [Column(TypeName = "int")]
    public short DatabaseId get; set;


    but once you run migrations you will get this error and this is generated by sql server.




    Column 'Databases.DatabaseId' is not the same data type as referencing column 'Clients.DatabaseId' in foreign key 'FK_Clients_Databases_DatabaseId'.




    And this makes perfect sense. What you are trying to achieve is not physically possible as SQL server requires foreign key to be same type otherwise you cannot build foreign key relationship.






    share|improve this answer























    • I'm not concerned about migrations since the application I'm writing does not own the database. However, this still does not work and throws: System.InvalidOperationException: An exception occurred while reading a database value for property 'Client.DatabaseId'. The expected type was 'System.Int16' but the actual value was of type 'System.Int32'. ---> System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.Int16'. I also tried going the other way and defining it as an int

      – jaredcnance
      Feb 27 '18 at 17:11












    • @jaredcnance it doesn't have anything to do with migrations it has everything to do with design. Your attempting to fit a Square Peg in a round HOLE. INT != SHORT in SQL SERVER, SHORT = SMALLINT, SMALLINT != INT in Sql Server. Truncation! EF is smart enough to know this... hence the error, and why ef core is rolling around on floor twitching..

      – mvermef
      Feb 27 '18 at 23:25












    • My comment about migrations was in response to the answer. I am aware that migrations is not the issue. I'm searching for a workaround to this problem because I cannot feasibly alter the database. Other applications depend on the current datatypes and would break if I altered the database. If this absolutely cannot be done, then fine I'll have to use Dapper or not use the navigation properties. My question is whether or not a workaround exists in EF Core.

      – jaredcnance
      Feb 28 '18 at 16:35












    • @jaredcnance you cannot do that physically, even Dapper will not work. and the end you will get exception foreign key is not of same type this is only possible if you remove the relation between your tables and handle all foreign keys manually. If you remove the relation then joins will not work in normal way (you will also lose the navigation properties)

      – Mujahid Daud Khan
      Mar 1 '18 at 8:40










    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%2f48998620%2fentity-framework-core-fk-with-different-datatype-than-pk%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    In EF Core 2.1 you can use value conversions, i.e.



    entityBuilder.Property(c => c.Id).HasConversion<string>(); 


    where the generic string is the database type and the destination is the model type. You can read further on https://docs.microsoft.com/es-es/ef/core/modeling/value-conversions






    share|improve this answer



























      2














      In EF Core 2.1 you can use value conversions, i.e.



      entityBuilder.Property(c => c.Id).HasConversion<string>(); 


      where the generic string is the database type and the destination is the model type. You can read further on https://docs.microsoft.com/es-es/ef/core/modeling/value-conversions






      share|improve this answer

























        2












        2








        2







        In EF Core 2.1 you can use value conversions, i.e.



        entityBuilder.Property(c => c.Id).HasConversion<string>(); 


        where the generic string is the database type and the destination is the model type. You can read further on https://docs.microsoft.com/es-es/ef/core/modeling/value-conversions






        share|improve this answer













        In EF Core 2.1 you can use value conversions, i.e.



        entityBuilder.Property(c => c.Id).HasConversion<string>(); 


        where the generic string is the database type and the destination is the model type. You can read further on https://docs.microsoft.com/es-es/ef/core/modeling/value-conversions







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 14 '18 at 15:05









        Tomas Lopez RodriguezTomas Lopez Rodriguez

        364




        364























            1














            You can bypass error generated by entity framework by using the following code to define your foreign key



            [Column(TypeName = "int")]
            public short DatabaseId get; set;


            but once you run migrations you will get this error and this is generated by sql server.




            Column 'Databases.DatabaseId' is not the same data type as referencing column 'Clients.DatabaseId' in foreign key 'FK_Clients_Databases_DatabaseId'.




            And this makes perfect sense. What you are trying to achieve is not physically possible as SQL server requires foreign key to be same type otherwise you cannot build foreign key relationship.






            share|improve this answer























            • I'm not concerned about migrations since the application I'm writing does not own the database. However, this still does not work and throws: System.InvalidOperationException: An exception occurred while reading a database value for property 'Client.DatabaseId'. The expected type was 'System.Int16' but the actual value was of type 'System.Int32'. ---> System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.Int16'. I also tried going the other way and defining it as an int

              – jaredcnance
              Feb 27 '18 at 17:11












            • @jaredcnance it doesn't have anything to do with migrations it has everything to do with design. Your attempting to fit a Square Peg in a round HOLE. INT != SHORT in SQL SERVER, SHORT = SMALLINT, SMALLINT != INT in Sql Server. Truncation! EF is smart enough to know this... hence the error, and why ef core is rolling around on floor twitching..

              – mvermef
              Feb 27 '18 at 23:25












            • My comment about migrations was in response to the answer. I am aware that migrations is not the issue. I'm searching for a workaround to this problem because I cannot feasibly alter the database. Other applications depend on the current datatypes and would break if I altered the database. If this absolutely cannot be done, then fine I'll have to use Dapper or not use the navigation properties. My question is whether or not a workaround exists in EF Core.

              – jaredcnance
              Feb 28 '18 at 16:35












            • @jaredcnance you cannot do that physically, even Dapper will not work. and the end you will get exception foreign key is not of same type this is only possible if you remove the relation between your tables and handle all foreign keys manually. If you remove the relation then joins will not work in normal way (you will also lose the navigation properties)

              – Mujahid Daud Khan
              Mar 1 '18 at 8:40















            1














            You can bypass error generated by entity framework by using the following code to define your foreign key



            [Column(TypeName = "int")]
            public short DatabaseId get; set;


            but once you run migrations you will get this error and this is generated by sql server.




            Column 'Databases.DatabaseId' is not the same data type as referencing column 'Clients.DatabaseId' in foreign key 'FK_Clients_Databases_DatabaseId'.




            And this makes perfect sense. What you are trying to achieve is not physically possible as SQL server requires foreign key to be same type otherwise you cannot build foreign key relationship.






            share|improve this answer























            • I'm not concerned about migrations since the application I'm writing does not own the database. However, this still does not work and throws: System.InvalidOperationException: An exception occurred while reading a database value for property 'Client.DatabaseId'. The expected type was 'System.Int16' but the actual value was of type 'System.Int32'. ---> System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.Int16'. I also tried going the other way and defining it as an int

              – jaredcnance
              Feb 27 '18 at 17:11












            • @jaredcnance it doesn't have anything to do with migrations it has everything to do with design. Your attempting to fit a Square Peg in a round HOLE. INT != SHORT in SQL SERVER, SHORT = SMALLINT, SMALLINT != INT in Sql Server. Truncation! EF is smart enough to know this... hence the error, and why ef core is rolling around on floor twitching..

              – mvermef
              Feb 27 '18 at 23:25












            • My comment about migrations was in response to the answer. I am aware that migrations is not the issue. I'm searching for a workaround to this problem because I cannot feasibly alter the database. Other applications depend on the current datatypes and would break if I altered the database. If this absolutely cannot be done, then fine I'll have to use Dapper or not use the navigation properties. My question is whether or not a workaround exists in EF Core.

              – jaredcnance
              Feb 28 '18 at 16:35












            • @jaredcnance you cannot do that physically, even Dapper will not work. and the end you will get exception foreign key is not of same type this is only possible if you remove the relation between your tables and handle all foreign keys manually. If you remove the relation then joins will not work in normal way (you will also lose the navigation properties)

              – Mujahid Daud Khan
              Mar 1 '18 at 8:40













            1












            1








            1







            You can bypass error generated by entity framework by using the following code to define your foreign key



            [Column(TypeName = "int")]
            public short DatabaseId get; set;


            but once you run migrations you will get this error and this is generated by sql server.




            Column 'Databases.DatabaseId' is not the same data type as referencing column 'Clients.DatabaseId' in foreign key 'FK_Clients_Databases_DatabaseId'.




            And this makes perfect sense. What you are trying to achieve is not physically possible as SQL server requires foreign key to be same type otherwise you cannot build foreign key relationship.






            share|improve this answer













            You can bypass error generated by entity framework by using the following code to define your foreign key



            [Column(TypeName = "int")]
            public short DatabaseId get; set;


            but once you run migrations you will get this error and this is generated by sql server.




            Column 'Databases.DatabaseId' is not the same data type as referencing column 'Clients.DatabaseId' in foreign key 'FK_Clients_Databases_DatabaseId'.




            And this makes perfect sense. What you are trying to achieve is not physically possible as SQL server requires foreign key to be same type otherwise you cannot build foreign key relationship.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Feb 27 '18 at 5:53









            Mujahid Daud KhanMujahid Daud Khan

            1,160917




            1,160917












            • I'm not concerned about migrations since the application I'm writing does not own the database. However, this still does not work and throws: System.InvalidOperationException: An exception occurred while reading a database value for property 'Client.DatabaseId'. The expected type was 'System.Int16' but the actual value was of type 'System.Int32'. ---> System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.Int16'. I also tried going the other way and defining it as an int

              – jaredcnance
              Feb 27 '18 at 17:11












            • @jaredcnance it doesn't have anything to do with migrations it has everything to do with design. Your attempting to fit a Square Peg in a round HOLE. INT != SHORT in SQL SERVER, SHORT = SMALLINT, SMALLINT != INT in Sql Server. Truncation! EF is smart enough to know this... hence the error, and why ef core is rolling around on floor twitching..

              – mvermef
              Feb 27 '18 at 23:25












            • My comment about migrations was in response to the answer. I am aware that migrations is not the issue. I'm searching for a workaround to this problem because I cannot feasibly alter the database. Other applications depend on the current datatypes and would break if I altered the database. If this absolutely cannot be done, then fine I'll have to use Dapper or not use the navigation properties. My question is whether or not a workaround exists in EF Core.

              – jaredcnance
              Feb 28 '18 at 16:35












            • @jaredcnance you cannot do that physically, even Dapper will not work. and the end you will get exception foreign key is not of same type this is only possible if you remove the relation between your tables and handle all foreign keys manually. If you remove the relation then joins will not work in normal way (you will also lose the navigation properties)

              – Mujahid Daud Khan
              Mar 1 '18 at 8:40

















            • I'm not concerned about migrations since the application I'm writing does not own the database. However, this still does not work and throws: System.InvalidOperationException: An exception occurred while reading a database value for property 'Client.DatabaseId'. The expected type was 'System.Int16' but the actual value was of type 'System.Int32'. ---> System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.Int16'. I also tried going the other way and defining it as an int

              – jaredcnance
              Feb 27 '18 at 17:11












            • @jaredcnance it doesn't have anything to do with migrations it has everything to do with design. Your attempting to fit a Square Peg in a round HOLE. INT != SHORT in SQL SERVER, SHORT = SMALLINT, SMALLINT != INT in Sql Server. Truncation! EF is smart enough to know this... hence the error, and why ef core is rolling around on floor twitching..

              – mvermef
              Feb 27 '18 at 23:25












            • My comment about migrations was in response to the answer. I am aware that migrations is not the issue. I'm searching for a workaround to this problem because I cannot feasibly alter the database. Other applications depend on the current datatypes and would break if I altered the database. If this absolutely cannot be done, then fine I'll have to use Dapper or not use the navigation properties. My question is whether or not a workaround exists in EF Core.

              – jaredcnance
              Feb 28 '18 at 16:35












            • @jaredcnance you cannot do that physically, even Dapper will not work. and the end you will get exception foreign key is not of same type this is only possible if you remove the relation between your tables and handle all foreign keys manually. If you remove the relation then joins will not work in normal way (you will also lose the navigation properties)

              – Mujahid Daud Khan
              Mar 1 '18 at 8:40
















            I'm not concerned about migrations since the application I'm writing does not own the database. However, this still does not work and throws: System.InvalidOperationException: An exception occurred while reading a database value for property 'Client.DatabaseId'. The expected type was 'System.Int16' but the actual value was of type 'System.Int32'. ---> System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.Int16'. I also tried going the other way and defining it as an int

            – jaredcnance
            Feb 27 '18 at 17:11






            I'm not concerned about migrations since the application I'm writing does not own the database. However, this still does not work and throws: System.InvalidOperationException: An exception occurred while reading a database value for property 'Client.DatabaseId'. The expected type was 'System.Int16' but the actual value was of type 'System.Int32'. ---> System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.Int16'. I also tried going the other way and defining it as an int

            – jaredcnance
            Feb 27 '18 at 17:11














            @jaredcnance it doesn't have anything to do with migrations it has everything to do with design. Your attempting to fit a Square Peg in a round HOLE. INT != SHORT in SQL SERVER, SHORT = SMALLINT, SMALLINT != INT in Sql Server. Truncation! EF is smart enough to know this... hence the error, and why ef core is rolling around on floor twitching..

            – mvermef
            Feb 27 '18 at 23:25






            @jaredcnance it doesn't have anything to do with migrations it has everything to do with design. Your attempting to fit a Square Peg in a round HOLE. INT != SHORT in SQL SERVER, SHORT = SMALLINT, SMALLINT != INT in Sql Server. Truncation! EF is smart enough to know this... hence the error, and why ef core is rolling around on floor twitching..

            – mvermef
            Feb 27 '18 at 23:25














            My comment about migrations was in response to the answer. I am aware that migrations is not the issue. I'm searching for a workaround to this problem because I cannot feasibly alter the database. Other applications depend on the current datatypes and would break if I altered the database. If this absolutely cannot be done, then fine I'll have to use Dapper or not use the navigation properties. My question is whether or not a workaround exists in EF Core.

            – jaredcnance
            Feb 28 '18 at 16:35






            My comment about migrations was in response to the answer. I am aware that migrations is not the issue. I'm searching for a workaround to this problem because I cannot feasibly alter the database. Other applications depend on the current datatypes and would break if I altered the database. If this absolutely cannot be done, then fine I'll have to use Dapper or not use the navigation properties. My question is whether or not a workaround exists in EF Core.

            – jaredcnance
            Feb 28 '18 at 16:35














            @jaredcnance you cannot do that physically, even Dapper will not work. and the end you will get exception foreign key is not of same type this is only possible if you remove the relation between your tables and handle all foreign keys manually. If you remove the relation then joins will not work in normal way (you will also lose the navigation properties)

            – Mujahid Daud Khan
            Mar 1 '18 at 8:40





            @jaredcnance you cannot do that physically, even Dapper will not work. and the end you will get exception foreign key is not of same type this is only possible if you remove the relation between your tables and handle all foreign keys manually. If you remove the relation then joins will not work in normal way (you will also lose the navigation properties)

            – Mujahid Daud Khan
            Mar 1 '18 at 8:40

















            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%2f48998620%2fentity-framework-core-fk-with-different-datatype-than-pk%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







            這個網誌中的熱門文章

            Barbados

            How to read a connectionString WITH PROVIDER in .NET Core?

            Node.js Script on GitHub Pages or Amazon S3