When creating a navigation property (link to another table), you must specify the column name to use as a foreign key. If you do not, EF assumes that it is a column named Objectname_Id.
You can see in the sql code that he called your column [Owner_Id]. The problem is that when you do this this way, you cannot control the data annotations for this column.
try it
public class Fund { [Key] public int FundId { get; set; } [Required] [Index("IX_FundNameAndOwner", IsUnique = true, Order = 1)] [Index("IX_FundIdentifierAndOwner", IsUnique = true, Order = 1)] public int OwnerId { get; set; } // <---- ADD THIS! public virtual ApplicationUser Owner { get; set; } [Required] [Index("IX_FundNameAndOwner", IsUnique = true, Order = 2)] [MaxLength(25)] public string Name { get; set; } [Required] [Index("IX_FundIdentifierAndOwner", IsUnique = true, Order = 2)] [MaxLength(25)] public string Identifier { get; set; } public double Balance { get; set; } }
Adding a column named ObjectId (or Objec_Id) EF by convention understands that the column is for the property owner.
This is the script generated by the migration:
CREATE TABLE [dbo].[Funds] ( [FundId] [int] NOT NULL IDENTITY, [OwnerId] [int] NOT NULL, [Name] [nvarchar](25) NOT NULL, [Identifier] [nvarchar](25) NOT NULL, [Balance] [float] NOT NULL, CONSTRAINT [PK_dbo.Funds] PRIMARY KEY ([FundId]) ) CREATE UNIQUE INDEX [IX_FundIdentifierAndOwner] ON [dbo].[Funds]([OwnerId], [Identifier]) CREATE UNIQUE INDEX [IX_FundNameAndOwner] ON [dbo].[Funds]([OwnerId], [Name])
Here is an explanation of the standard code first conventions .
source share