I am using C# EF code-first. I have the following 2 classes:
public class Om_Currency
{
[Key]
public Int16 CurrencyID { get; set; }
public String CurrencySymbol { get; set; }
public Boolean IsActive { get; set; }
public Int32 CountryID { get; set; }
public virtual Om_Country Country { get; set; }
}
public class Om_Country
{
[Key]
public Int16 CountryID { get; set; }
public String CountryName { get; set; }
public Boolean IsActive { get; set; }
public Int32 CurrencyID { get; set; }
public virtual Om_Currency Currency { get; set; }
}
Now, I am trying to implement an 1-1 relationship between these 2 classes. So that I can get Currency details from Country and Country details can be fetched from Currency.
modelBuilder
.Entity<Om_Country>()
.HasOptional(f => f.Currency)
.WithRequired(s => s.Country);
modelBuilder
.Entity<Om_Currency>()
.HasOptional(f => f.Country)
.WithRequired(s => s.Currency);
But I get this error:
The navigation property 'Country' declared on type
'ObjectModel.Country.Om_Currency' has been configured with conflicting
multiplicities.
Am I doing something wrong?
This is the mapping class for Country:
public class CountryMap : EntityTypeConfiguration<Om_Country>
{
public CountryMap()
{
Property(x => x.CountryID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(x => x.CountryName)
.IsRequired()
.HasMaxLength(100)
.HasColumnAnnotation
(
IndexAnnotation.AnnotationName,
new IndexAnnotation
(
new IndexAttribute("U_CountryName", 1) { IsUnique = true }
)
);
Property(x => x.IsActive).IsRequired();
Property(x => x.CurrencyID).IsRequired();
ToTable(clsCommon.tblCountry);
}
}
and this is the mapping class for Currency:
public class CurrencyMap : EntityTypeConfiguration<Om_Currency>
{
public CurrencyMap()
{
Property(x => x.CurrencyID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(x => x.CurrencySymbol)
.IsRequired()
.IsVariableLength()
.HasMaxLength(50)
.HasColumnAnnotation
(
IndexAnnotation.AnnotationName,
new IndexAnnotation
(
new IndexAttribute("U_CurrencySymbol", 1) { IsUnique = true }
)
);
Property(x => x.IsActive).IsRequired();
Property(x => x.CountryID).IsRequired();
ToTable(clsCommon.tblCurrency);
}
}
I figured out the issue. I got the Solution from here
Instead of below
modelBuilder
.Entity<Om_Country>()
.HasOptional(f => f.Currency)
.WithRequired(s => s.Country);
modelBuilder
.Entity<Om_Currency>()
.HasOptional(f => f.Country)
.WithRequired(s => s.Currency);
It should be below
modelBuilder.Entity<Om_Country>()
.HasRequired(x => x.Currency).WithMany()
.HasForeignKey(x => x.CurrencyID).WillCascadeOnDelete(false);
modelBuilder.Entity<Om_Currency>()
.HasRequired(x => x.Country).WithMany()
.HasForeignKey(x => x.CountryID).WillCascadeOnDelete(false);
Related
On https://learn.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key#joining-relationships-configuration they have the following example of how to specify a many-to-many relationship in Entity Framework Core:
modelBuilder.Entity<Post>()
.HasMany(p => p.Tags)
.WithMany(p => p.Posts)
.UsingEntity<Dictionary<string, object>>(
"PostTag",
j => j
.HasOne<Tag>()
.WithMany()
.HasForeignKey("TagId")
.HasConstraintName("FK_PostTag_Tags_TagId")
.OnDelete(DeleteBehavior.Cascade),
j => j
.HasOne<Post>()
.WithMany()
.HasForeignKey("PostId")
.HasConstraintName("FK_PostTag_Posts_PostId")
.OnDelete(DeleteBehavior.ClientCascade));
How do I do the same thing, but specify that PostTag is part of a schema other than the default one?
For instance, Test.PostTag and [Test].[PostTag] do not work. When trying to access the resource, it just results in the exception Microsoft.Data.SqlClient.SqlException: 'Invalid object name 'PostTag'.' being thrown. So it seems to ignore the schema name Test when I try to specify it.
What I did was to do what they have written on the page https://www.learnentityframeworkcore.com/configuration/many-to-many-relationship-configuration. In their example, they have the following two classes:
public class Book
{
public int BookId { get; set; }
public string Title { get; set; }
public Author Author { get; set; }
public ICollection<BookCategory> BookCategories { get; set; }
}
public class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public ICollection<BookCategory> BookCategories { get; set; }
}
And then they made the following class to connect them through a many-to-many relationship:
public class BookCategory
{
public int BookId { get; set; }
public Book Book { get; set; }
public int CategoryId { get; set; }
public Category Category { get; set; }
}
And then they have the following configuration:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<BookCategory>()
.HasKey(bc => new { bc.BookId, bc.CategoryId });
modelBuilder.Entity<BookCategory>()
.HasOne(bc => bc.Book)
.WithMany(b => b.BookCategories)
.HasForeignKey(bc => bc.BookId);
modelBuilder.Entity<BookCategory>()
.HasOne(bc => bc.Category)
.WithMany(c => c.BookCategories)
.HasForeignKey(bc => bc.CategoryId);
}
In my case, I configured the connection class like this:
internal class AccountRuleEntityTypeConfiguration : IEntityTypeConfiguration<CompAccountRule>
{
public void Configure(EntityTypeBuilder<AccountRule> builder)
{
builder
.ToTable("AccountRules", "Compliance");
builder
.HasKey(x => new { x.AccountId, x.RuleInstanceId });
builder
.HasOne(x => x.Account)
.WithMany(x => x.AccountRules)
.HasForeignKey(x => x.AccountId);
builder
.HasOne(x => x.RuleInstance)
.WithMany(x => x.AccountRules)
.HasForeignKey(x => x.RuleInstanceId);
}
}
Account belongs to the default namespace, RuleInstance belongs to the Compliance namespace, and this connection table AccountRule also belongs to the Compliance namespace, which is I'm able to configure through the statement builder.ToTable("AccountRules", "Compliance");.
I have 3 entities mapped to each other with one-to-many relationship, one of them should be mapped to both of them which is resulting in unwanted many-to-many relationship.
Here is the logic behind the mapping:
User can have many Posts; Post has only one user.
User can have many Categories; Category has only one user.
Category can have many posts; Post has only one category.
Here is my code:
User
Table("Users")]
Public Class User
{
[Key]
public int UserId { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public string UserName { get; set; }
public DateTime CreatedAt { get; set; }
public ICollection<Posts> Posts { get; set; }
public ICollection<Category> Categories { get; set; }
}
Post
[Table("Posts")]
public class Post
{
[Key]
public int PostId { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Description { get; set; }
[Required]
public string Text { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime? UpdatedAt { get; set; }
public int UserId { get; set; }
public User User { get; set; }
public int CategoryId { get; set; }
public Category Category { get; set; }
}
Category
[Table("Categories")]
public class Category
{
[Key]
public int CategoryId { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
public DateTime CreatedAt { get; set; }
public int UserId { get; set; }
public User User { get; set; }
public ICollection<Post> Posts { get; set; }
}
My Db Context
public class BlogContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Post> Posts{ get; set; }
public DbSet<Category> Categories { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>(entity =>
{
entity.HasMany<Post>(s => s.Posts)
.WithOne(u => u.User)
.HasForeignKey(s => s.UserId)
.OnDelete(DeleteBehavior.Restrict);
entity.HasMany<Category>(c => c.Categories)
.WithOne(u => u.User)
.HasForeignKey(c => c.UserId)
.OnDelete(DeleteBehavior.Restrict);
entity.Property(u => u.CreatedAt)
.HasDefaultValueSql("SYSUTCDATETIME()");
});
modelBuilder.Entity<Post>(entity =>
{
entity.HasOne<Category>(s => s.Category)
.WithMany(c => c.Posts)
.HasForeignKey(s => s.PostId);
entity.HasOne<User>(s => s.User)
.WithMany(u => u.Posts)
.HasForeignKey(s => s.PostId);
entity.Property(s => s.CreatedAt)
.HasDefaultValueSql("SYSUTCDATETIME()");
});
modelBuilder.Entity<Category>(entity =>
{
entity.HasMany<Post>(c => c.Posts)
.WithOne(s => s.Category)
.HasForeignKey(c => c.PostId)
.OnDelete(DeleteBehavior.Restrict);
entity.Property(c => c.CreatedAt)
.HasDefaultValueSql("SYSUTCDATETIME()");
});
}
}
I ran into this problem when inserting posts:
The property 'PostId' on entity type 'Post' has a temporary value
What I understood is that I caused many-to-many relationship with the way that I've implemented the DbContext. How can I fix it? Thanks for helping.
You didn't configure the foreign key correctly. Let's review your code of Entity<Post>(entity=>{ /* ... */ }):
modelBuilder.Entity<Post>(entity =>
{
entity.HasOne<Category>(s => s.Category)
.WithMany(c => c.Posts)
.HasForeignKey(s => s.PostId); // line A: it is not correct!
entity.HasOne<User>(s => s.User)
.WithMany(u => u.Posts)
.HasForeignKey(s => s.PostId); // line B: it is not correct!
entity.Property(s => s.CreatedAt)
.HasDefaultValueSql("SYSUTCDATETIME()");
});
Note the line A and line B are not correct. As in both cases, the dependent entity is Post. Your code will result in a foreign key as below:
CREATE TABLE [Posts] (
[PostId] int NOT NULL,
[Title] nvarchar(max) NOT NULL,
[Description] nvarchar(max) NOT NULL,
[Text] nvarchar(max) NOT NULL,
[CreatedAt] datetime2 NOT NULL DEFAULT (SYSUTCDATETIME()),
[UpdatedAt] datetime2 NULL,
[UserId] int NOT NULL,
[CategoryId] int NOT NULL,
CONSTRAINT [PK_Posts] PRIMARY KEY ([PostId]),
CONSTRAINT [FK_Posts_Categories_PostId] FOREIGN KEY ([PostId]) REFERENCES [Categories] ([CategoryId]) ON DELETE NO ACTION,
CONSTRAINT [FK_Posts_Users_PostId] FOREIGN KEY ([PostId]) REFERENCES [Users] ([UserId]) ON DELETE NO ACTION
);
So you need change your code as below:
modelBuilder.Entity<Post>(entity =>
{
entity.HasOne<Category>(s => s.Category)
.WithMany(c => c.Posts)
//.HasForeignKey(s => s.PostId);
.HasForeignKey(s => s.CategoryId);
entity.HasOne<User>(s => s.User)
.WithMany(u => u.Posts)
//.HasForeignKey(s => s.PostId);
.HasForeignKey(s => s.UserId);
entity.Property(s => s.CreatedAt)
.HasDefaultValueSql("SYSUTCDATETIME()");
});
Because of the same reason, you should also change the part of Entity<Category>(entity=>{ /* ... */ }) as below:
modelBuilder.Entity<Category>(entity =>
{
entity.HasMany<Post>(c => c.Posts)
.WithOne(s => s.Category)
//.HasForeignKey(c => c.PostId) // remove this line
.HasForeignKey(c => c.CategoryId) // add this line
.OnDelete(DeleteBehavior.Restrict);
entity.Property(c => c.CreatedAt)
.HasDefaultValueSql("SYSUTCDATETIME()");
});
You made a mistake in
modelBuilder.Entity<Post>(entity =>
{
entity.HasOne<Category>(s => s.Category)
.WithMany(c => c.Posts)
.HasForeignKey(s => s.PostId);
entity.HasOne<User>(s => s.User)
.WithMany(u => u.Posts)
.HasForeignKey(s => s.PostId);
entity.Property(s => s.CreatedAt)
.HasDefaultValueSql("SYSUTCDATETIME()");
});
Table category model has not PostId, and User model has not too. Correct this.
I want to create database EF migrations via the developer command prompt for VS2015. When I try to use this command line:
dotnet ef migrations add v1
I get this error:
The property 'partCategoriess' cannot be added to the entity type
'PartCategoryPart' because a navigation property with the same name
already exists on entity type 'PartCategoryPart'.
Is anything wrong with the DbContext? I am trying to create a many-to-many table between categoryParts and parts.
public class ShoppingDbContext : IdentityDbContext<User>
{
public ShoppingDbContext(DbContextOptions options) : base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
}
public DbSet<PartCategory> PartCategories { get; set; }
public DbSet<Part> Parts { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<PartCategoryPart>()
.HasKey(t => new { t.partCategoriess, t.Part });
modelBuilder.Entity<PartCategoryPart>()
.HasOne(pt => pt.partCategoriess)
.WithMany(p => p.PartCategoryPart)
.HasForeignKey(pt => pt.PartCategoryId);
modelBuilder.Entity<PartCategoryPart>()
.HasOne(pt => pt.Part)
.WithMany(t => t.PartCategoryPart)
.HasForeignKey(pt => pt.PartId);
}
}
public class PartCategoryPart
{
public int Id { get; set; }
public int PartCategoryId { get; set; }
public PartCategory partCategoriess { get; set; }
public int PartId { get; set; }
public Part Part { get; set; }
}
public class PartCategory
{
public int PartCategoryId { get; set; }
public string Category { get; set; }
public List<ProductPartCategory> ProductPartCategories { get; set; }
public List<PartCategoryPart> PartCategoryPart { get; set; }
}
public class Part
{
public int PartId { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public double? Price { get; set; }
public List<PartCategoryPart> PartCategoryPart { get; set; }
}
The problem here is how you are defining the primary key for the PartCategoryPart intermediate entity. You are using the navigation properties to define the PK and you have to use the FKs like this:
modelBuilder.Entity().HasKey(t => new { t.PartCategoryId, t.PartId});
Referring to my own assignment, here's how you properly create an entity. You did not define a key..
modelBuilder.Entity<Price>()
.HasKey(input => input.PriceId)
.HasName("PrimaryKey_Price_PriceId");
// Provide the properties of the PriceId column
modelBuilder.Entity<Price>()
.Property(input => input.PriceId)
.HasColumnName("PriceId")
.HasColumnType("int")
.UseSqlServerIdentityColumn()
.ValueGeneratedOnAdd()
.IsRequired();
//modelBuilder.Entity<Price>()
// .Property(input => input.MetricId)
// .HasColumnName("MetricId")
// .HasColumnType("int")
// .IsRequired();
modelBuilder.Entity<Price>()
.Property(input => input.Value)
.HasColumnName("Value")
.HasColumnType("DECIMAL(19,4)")
.IsRequired();
modelBuilder.Entity<Price>()
.Property(input => input.RRP)
.HasColumnName("RRP")
.HasColumnType("DECIMAL(19,4)")
.IsRequired(false);
modelBuilder.Entity<Price>()
.Property(input => input.CreatedAt)
.HasDefaultValueSql("GetDate()");
modelBuilder.Entity<Price>()
.Property(input => input.DeletedAt)
.IsRequired(false);
// Two sets of Many to One relationship between User and ApplicationUser entity (Start)
modelBuilder.Entity<Price>()
.HasOne(userClass => userClass.CreatedBy)
.WithMany()
.HasForeignKey(userClass => userClass.CreatedById)
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
modelBuilder.Entity<Price>()
.HasOne(userClass => userClass.DeletedBy)
.WithMany()
.HasForeignKey(userClass => userClass.DeletedById)
.OnDelete(DeleteBehavior.Restrict);
Notice that after identifying which is the key you still need to declare its properties before you declare any relationships.
modelBuilder.Entity<Price>()
.HasKey(input => input.PriceId)
.HasName("PrimaryKey_Price_PriceId");
// Provide the properties of the PriceId column
modelBuilder.Entity<Price>()
.Property(input => input.PriceId)
.HasColumnName("PriceId")
.HasColumnType("int")
.UseSqlServerIdentityColumn()
.ValueGeneratedOnAdd()
.IsRequired();
Hi! I have some relational issues between two tables, one - to - many.
The whole concept is as follows:
Table 1: Country:
Besides it's own fields it also contains two ICollections where one points to a collection of regions and the other on cities.
Table 2: Region
Besides it's own fields, it also contains a CountryId and a ICollection of Cities.
Table 3: City
Besides it's own fields, it also contains a CountryId and a RegionId (where regionId can be nullable).
The principal idea is that a Country can have region(s) or/and city(ies).
This means that each foreign key from region/city to the CountryId cannot be null. But, the foreign key from City To Region is allowed to be null, since "some" Countries, in this case, regions is unnecessary.
Observe that all three tables is also refering, with an ICollection, to a middle table wich in turn stores the relation between them.
Country Entity:
public class Country
{
public Guid Id { get; set; }
public int CountryId { get; set; }
public Guid ComponentId { get; set; }
public string NumCode { get; set; }
public string Code2 { get; set; }
public string Code3 { get; set; }
public virtual ICollection<Region> Regions { get; set; }
public virtual ICollection<City> Cities { get; set; }
public virtual ICollection<AdvertGeography> AdvertsGeographies { get; set; }
}
public class CountryMap()
{
// Primary Key
HasKey(t => t.Id);
Property(e => e.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
// Unique Index
Property(e => e.ComponentId)
.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_Unique_Component", 1) { IsUnique = true }));
Property(e => e.CountryId)
.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_Unique_Country", 1) { IsUnique = true }));
// Properties
// Table & Column Mappings
ToTable("Country");
Property(e => e.Id).HasColumnName("Id");
Property(e => e.CountryId).HasColumnName("CountryId");
Property(e => e.ComponentId).HasColumnName("ComponentId");
Property(e => e.Code2).HasColumnName("Code2");
Property(e => e.Code3).HasColumnName("Code3");
Property(e => e.NumCode).HasColumnName("NumCode");
// Relationships
HasMany(t => t.Regions)
.WithRequired(t => t.Country).WillCascadeOnDelete(false);
HasMany(t => t.Cities)
.WithRequired(t => t.Country).WillCascadeOnDelete(false);
}
Region Entity:
public class Region
{
public Region()
{
this.Cities = new HashSet<City>();
}
public Guid Id { get; set; }
public Guid CountryId { get; set; }
public virtual Country Country { get; set; }
public string Name { get; set; }
public virtual ICollection<Office> Offices { get; set; }
public virtual ICollection<City> Cities { get; set; }
public virtual ICollection<OpenApplication> OpenApplications { get; set; }
public virtual ICollection<Subscription> Subscriptions { get; set; }
public virtual ICollection<AdvertGeography> AdvertsGeographies { get; set; }
}
public class RegionMap()
{
// Primary Key
HasKey(t => t.Id);
Property(e => e.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
// Unique Index
Property(e => e.Name)
.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_Unique", 1) { IsUnique = true }));
Property(e => e.CountryId)
.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_Unique", 2) { IsUnique = true }));
// Properties
Property(e => e.Name).IsRequired().HasMaxLength(512);
// Table & Column Mappings
ToTable("Region");
Property(e => e.Id).HasColumnName("Id");
Property(e => e.Name).HasColumnName("Name");
Property(e => e.CountryId).HasColumnName("CountryId");
// Relationships
HasMany(t => t.Subscriptions)
.WithMany(t => t.Regions);
HasMany(t => t.OpenApplications)
.WithMany(t => t.Regions);
HasMany(t => t.Offices)
.WithRequired(t => t.Region);
HasMany(t => t.Cities)
.WithRequired(t => t.Region);
HasRequired(t => t.Country).WithMany(t => t.Regions).WillCascadeOnDelete(false);
}
City Entity:
public class City
{
public Guid Id { get; set; }
public Guid CountryId { get; set; }
public virtual Country Country { get; set; }
public Guid? RegionId { get; set; }
public virtual Region Region { get; set; }
public string Name { get; set; }
public virtual ICollection<AdvertGeography> AdvertsGeographies { get; set; }
}
public class CityMap()
{
//Primary Key
HasKey(e => e.Id);
Property(e => e.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
//Unique Index
Property(e => e.Name)
.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_Unique", 1) { IsUnique = true }));
//Properties
Property(e => e.Name).IsRequired().HasMaxLength(512);
//Table & Column Mappings
ToTable("City");
Property(e => e.Id).HasColumnName("Id");
Property(e => e.Name).HasColumnName("Name");
Property(e => e.CountryId).HasColumnName("CountryId");
Property(e => e.RegionId).HasColumnName("RegionId");
// Relationships
HasRequired(t => t.Country).WithMany(t => t.Cities).WillCascadeOnDelete(false);
HasOptional(t => t.Region).WithMany(t => t.Cities).HasForeignKey(t => t.RegionId);
}
/J
Anybody have an idea? Glad for any help
Best regards
Actually I have solved it now. I missied this in RegionMap:
Quite trivial, but when you stare too long at your code, these things easily slips through.
HasMany(t => t.Cities)
.WithRequired(t => t.Region);
Should be
HasMany(t => t.Cities)
.WithOptional(t => t.Region);
Thanks anyway.
/J
I have a problem with mapping my classes using code first and Entity Type Configuration.
I have a class User
public class User
{
public virtual UserData UserData { get; set; }
public Guid UserId { get; set; }
public string UserName { get; set; }
public virtual string PasswordHash { get; set; }
public virtual string SecurityStamp { get; set; }
public string Email { get; set; }
which is a User Table. And a UserData - which will be a table contains UserData as Name, LastName etc.
I want to use UserId as Forgein Key one-to-zer-or-one. For one user there will be only one UserData
public class UserData
{
public long Id { get; set; }
public Guid UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual User User { get; set; }
}
But can't quite figure out how to do the mapping
internal UserConfiguration()
{
ToTable("User");
HasKey(x => x.UserId)
.Property(x => x.UserId)
.HasColumnName("UserId")
.HasColumnType("uniqueidentifier")
.IsRequired();
... properties mapping
HasOptional(x => x.UserData).
WithRequired(x => x.User); ?? is this ok?
}
and the UserData
internal UserDataConfiguration()
{
ToTable("UserData");
HasKey(x => x.Id)
.Property(x => x.Id)
.HasColumnName("Id")
.HasColumnType("bigint")
.IsRequired();
Property(x => x.FirstName)
.HasColumnName("FirstName")
.HasColumnType("nvarchar")
.HasMaxLength(255);
Property(x => x.LastName)
.HasColumnName("LastName")
.HasColumnType("nvarchar");
Property(x => x.UserId)
.HasColumnName("UserId")
.HasColumnType("uniqueidentifier")
.IsRequired();
?? is this ok?
}
For User in UserConfiguration() to map one-to-zero-or-one relationship you can define as:
HasOptional(x => x.UserData).WithRequired(x => x.User);
For a 1:0..1 relationship in Entity Framework, the primary key for the optional side is also the foreign key, so you can set it up like this:
UserConfiguration()
{
ToTable("User");
HasKey(x => x.UserId)
Property(x => x.UserId)
.HasColumnName("UserId")
.HasColumnType("uniqueidentifier")
.IsRequired();
// you could define the relationship here as well, I moved it
// to UserDataConfiguration to make it easier to explain
// other properties
}
UserDataConfiguration()
{
ToTable("UserData");
HasKey(x => x.UserId);
Property(x => x.UserId)
.HasColumnName("UserId")
.HasColumnType("uniqueidentifier")
.IsRequired();
// This makes UserData's primary key the foreign key by default
HasRequired(x => x.User).WithOptional(x => x.UserData);
// other properties
}
You can't have a separate primary key for UserData.