My table is as follows:
create table Entities(
EntityId bigint not null identity(1, 1),
Name nvarchar(64) not null,
ParentEntityId bigint null
)
alter table Entities add constraint PK primary key (EntityId)
alter table Entities add constraint FK foreign key (ParentEntityId) references Entities(EntityId)
My model looks like this:
public class Entity
{
[Required]
public virtual long EntityId { get; set; }
[Required]
public virtual string Name { get; set; }
public virtual long? ParentEntityId { get; set; }
public virtual Entity ParentEntity { get; set; }
}
and I'm trying to map the ParentEntity property with fluent api mapping, but I couldn't get this to work. How can I do it?
Thanks in advance!
EDIT: Fixed code discrepancy.
This fluent will work for you:
modelBuilder.Entity<Entity>()
.HasOptional(e => e.ParentEntity)
.WithMany()
.HasForeignKey(e => e.ParentEntityId );
Created this database for me:
Related
I use in some project EF code First with TPH (in part of classes)
I have class like this:
namespace Billing.Model.Domain.Entities.BilProject
{
[Table("ProjectPriceList")]
public abstract class ProjectPriceList
{
[Key, Column("ProjectId", Order = 0)]
public int ProjectId { get; set; }
[Key, Column("PriceListId", Order = 1)]
public int PriceListId { get; set; }
[Key, Column("PriceListSourceType", Order = 2)]
public int PriceListSourceType { get; set; }
[ForeignKey("PriceListSourceType")]
public virtual BillingProjectCode PriceListSourceTypeCode { get; set; }
public int AddUsrnm { get; set; }
public DateTime AddTmstmp { get; set; }
[ForeignKey("ProjectId")]
public virtual BillingProject BillingProject { get; set; }
public virtual SnapShotPriceList SnapShotPriceList{ get; set; }
}
public class BillingProjectPriceList : ProjectPriceList
{
[ForeignKey("PriceListId")]
public virtual PriceList PriceList { get; set; }
}
public class EstimateProjectPriceList : ProjectPriceList
{
}
}
When I try to generate sql code to create a data base by
Update-Database -Script from console
I receive this SQL as result:
CREATE TABLE [dbo].[ProjectPriceList] (
[ProjectId] [int] NOT NULL,
[PriceListId] [int] NOT NULL,
[PriceListSourceType] [int] NOT NULL,
[AddUsrnm] [int] NOT NULL,
[AddTmstmp] [datetime] NOT NULL,
[Discriminator] [nvarchar](128) NOT NULL,
CONSTRAINT [PK_dbo.ProjectPriceList] PRIMARY KEY ([ProjectId], [PriceListId], [PriceListSourceType])
)
CREATE INDEX [IX_ProjectId] ON [dbo].[ProjectPriceList]([ProjectId])
CREATE INDEX [IX_PriceListId] ON [dbo].[ProjectPriceList]([PriceListId])
CREATE INDEX [IX_PriceListSourceType] ON [dbo].[ProjectPriceList]([PriceListSourceType])
ALTER TABLE [dbo].[ProjectPriceList] ADD CONSTRAINT [FK_dbo.ProjectPriceList_dbo.BillingProject_ProjectId] FOREIGN KEY ([ProjectId]) REFERENCES [dbo].[BillingProject] ([ProjectId]) ON DELETE CASCADE
ALTER TABLE [dbo].[ProjectPriceList] ADD CONSTRAINT [FK_dbo.ProjectPriceList_dbo.BillingProjectCode_PriceListSourceType] FOREIGN KEY ([PriceListSourceType]) REFERENCES [dbo].[BillingProjectCode] ([CodeId]) ON DELETE CASCADE
ALTER TABLE [dbo].[ProjectPriceList] ADD CONSTRAINT [FK_dbo.ProjectPriceList_dbo.PriceList_PriceListId] FOREIGN KEY ([PriceListId]) REFERENCES [dbo].[PriceList] ([PriceListId]) ON DELETE CASCADE
The last FK Constraint is redudant and make me trouble if i try add new EstimateProjectPriceList.
My question is
How to stop create this FK by some code Data Annotations or Fluent Api in OnModelCreating ?
Thnx for any help..
How do you specify a custom column name with a HasOne relationship in EF7?
Consider the following sample classes:
public class House
{
public int Id { get; set; }
public int BedroomCount { get; set; }
public Address Address { get; set; }
}
public class Address
{
public int Id { get; set; }
public string StreetName { get; set; }
public string StreetNumber { get; set; }
}
And this fluent configuration:
modelBuilder.Entity<House>()
.HasOne(x => x.Address)
.WithOne()
.OnDelete(DeleteBehavior.Cascade);
Which leads to this DB configuration:
CREATE TABLE [House] (
[Id] int NOT NULL IDENTITY,
[AddressId] int,
[BedroomCount] int NOT NULL,
CONSTRAINT [PK_House] PRIMARY KEY ([Id]),
CONSTRAINT [FK_House_Address_AddressId] FOREIGN KEY ([AddressId]) REFERENCES [Address] ([Id]) ON DELETE CASCADE);
CREATE TABLE [Address] (
[Id] int NOT NULL IDENTITY,
[StreetName] nvarchar(max),
[StreetNumber] nvarchar(max),
CONSTRAINT [PK_Address] PRIMARY KEY ([Id]));
How do I specify a column name other than "AddressId" on the House table? I cannot find a method similar to HasColumnName like there is on non-navigation properties.
I'm using Entity Framework 7 RC1-Final.
You can use Data Annotations to configure the foreign key of your relationship.
public int AddressID { get; set; }
[ForeignKey("AddressID")]
public Address Address { get; set; }
This requires a property that will be used as the foreign key in your relationship. Also, note that it is recommended that you have a explicit foreign key for your relationships other than a shadow foreign key. This will prevent you to have a lot of problems when inserting/updating since you don't need to set the entire navigation property Address to save a House entity. See the problem here
Not tested but perhaps this could work (can't find a way to install EF7 right now)
modelBuilder.Entity<House>()
.HasOne(x => x.Address)
.WithOne()
.OnDelete(DeleteBehavior.Cascade);
.HasForeignKey(x => x.AddressID);
You can check here for more examples: Foreign Key Relationships EF7
You can get property first from modelBuilder.Entity<House>().Metadata.GetProperties() list and then set its name
property.Relational().ColumnName = "YouCustomId"
In my Code First for this application I have defined a foreign key as nullable. However, when I try to add a record without that key, I still get a Foreign Key constraint error:
The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_dbo.RequestReview_dbo.CustomForm_ReviewFormId\". The conflict occurred in database \"Mkp\", table \"dbo.CustomForm\", column 'CustomFormId'.\r\nThe statement has been terminated.
How should I be defining the relationship so that the key constraint is not enforced?
My code first model defines the field like this:
[Key, ForeignKey("Resource"), DatabaseGenerated(DatabaseGeneratedOption.None)]
public Guid RequestReviewId { get; set; } // My Primary Key
public virtual Resource Resource { get; set; }
public Guid? ReviewFormId { get; set; } // Foreign Key
[ForeignKey("ReviewFormId")]
public CustomForm ReviewForm { get; set; }
(I did try searching, but I'm not sure I searched with the right terminology.)
Edit/Update:
If I remove the ForeignKey tag, I still get migration trying to create a relationship, but this time called ReviewForm_CustomFormId. How can I avoid this?
Updated version of the model:
[Key, ForeignKey("Resource"), DatabaseGenerated(DatabaseGeneratedOption.None)]
public Guid RequestReviewId { get; set; } // My Primary Key
public virtual Resource Resource { get; set; }
public Guid? ReviewFormId { get; set; } // Foreign Key
public CustomForm ReviewForm { get; set; }
Give it a separate primary key field as well as your foreign key:
public int ID { get; set; }
public Guid? ReviewFormId { get; set; }
[ForeignKey("ReviewFormId")]
public CustomForm ReviewForm { get; set; }
Doing this I was able to insert records that have a null ReviewFormId.
One solution i see is that you could use this colunm ReviewFormId as an implicite foreign key. What i mean is : don't define it as a foreign key, just a regular data instead, and only YOU will know that the data inside it represent a foreign key, but don't tell entity that it is a foreign key because GUID just dosen't accept nullable foreign key.
I have 2 classes: Client and Survey.
Each Client can have many surveys - but only one default survey.
I have defined the classes like this:
public class Client
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public string ClientName { get; set; }
public Nullable<int> DefaultSurveyID { get; set; }
[ForeignKey("DefaultSurveyID")]
public virtual Survey DefaultSurvey { get; set; }
public virtual ICollection<Survey> Surveys { get; set; }
}
public class Survey
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public string SurveyName { get; set; }
[Required]
public int ClientID { get; set; }
[ForeignKey("ClientID")]
public virtual Client Client { get; set; }
}
This creates the Client table as I expect:
[dbo].[Clients]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[ClientName] [nvarchar](max) NULL,
[DefaultSurveyID] [int] NULL
)
But the Survey table has an extra foreign key:
[dbo].[Surveys]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[SurveyName] [nvarchar](max) NULL,
[ClientID] [int] NOT NULL,
[Client_ID] [int] NULL
)
Why is Code First generating this relationship and how to I tell it not to?
The problem is that when you have multiple relationships between two entities, EF Code First isn't able to find out which navigation properties match up, unless, you tell it how, here is the code:
public class Client
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public string ClientName { get; set; }
/****Change Nullable<int> by int?, looks better****/
public int? DefaultSurveyID { get; set; }
/****You need to add this attribute****/
[InverseProperty("ID")]
[ForeignKey("DefaultSurveyID")]
public virtual Survey DefaultSurvey { get; set; }
public virtual ICollection<Survey> Surveys { get; set; }
}
With your previous version, EF was creating that extra relationship because it didn't know that the DefaultSurvey property was referencing the ID of the Survey class, but you can let it know that, adding the attribute InverseProperty whose parameter is the name of the property in Survey you need DefaultSurvey to match with.
You can do it using code-first, but not being a code first expert I cheated :-)
1) I created the tables and relationships (as above without the extra Client_ID) in the database using SMS
2) I used Reverse Engineer Code First to create the required classes and mappings
3) I dropped the database and recreated it using context.Database.Create()
Original table defs:
CREATE TABLE [dbo].[Client](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NULL,
[DefaultSurveyId] [int] NULL,
CONSTRAINT [PK_dbo.Client] PRIMARY KEY NONCLUSTERED
(
[Id] ASC
)
)
CREATE TABLE [dbo].[Survey](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NULL,
[ClientId] [int] NULL,
CONSTRAINT [PK_dbo.Survey] PRIMARY KEY NONCLUSTERED
(
[Id] ASC
)
)
Plus foreign keys
ALTER TABLE [dbo].[Survey] WITH CHECK
ADD CONSTRAINT [FK_dbo.Survey_dbo.Client_ClientId] FOREIGN KEY([ClientId])
REFERENCES [dbo].[Client] ([Id])
ALTER TABLE [dbo].[Client] WITH CHECK
ADD CONSTRAINT [FK_dbo.Client_dbo.Survey_DefaultSurveyId]
FOREIGN KEY([DefaultSurveyId]) REFERENCES [dbo].[Survey] ([Id])
Code generated by reverse engineering:
public partial class Client
{
public Client()
{
this.Surveys = new List<Survey>();
}
public int Id { get; set; }
public string Name { get; set; }
public int? DefaultSurveyId { get; set; }
public virtual Survey DefaultSurvey { get; set; }
public virtual ICollection<Survey> Surveys { get; set; }
}
public partial class Survey
{
public Survey()
{
this.Clients = new List<Client>();
}
public int Id { get; set; }
public string Name { get; set; }
public int? ClientId { get; set; }
public virtual ICollection<Client> Clients { get; set; }
public virtual Client Client { get; set; }
}
public class ClientMap : EntityTypeConfiguration<Client>
{
#region Constructors and Destructors
public ClientMap()
{
// Primary Key
this.HasKey(t => t.Id);
// Properties
this.Property(t => t.Name).HasMaxLength(50);
// Table & Column Mappings
this.ToTable("Client");
this.Property(t => t.Id).HasColumnName("Id");
this.Property(t => t.Name).HasColumnName("Name");
this.Property(t => t.DefaultSurveyId).HasColumnName("DefaultSurveyId");
// Relationships
this.HasOptional(t => t.DefaultSurvey)
.WithMany(t => t.Clients).HasForeignKey(d => d.DefaultSurveyId);
}
#endregion
}
public class SurveyMap : EntityTypeConfiguration<Survey>
{
#region Constructors and Destructors
public SurveyMap()
{
// Primary Key
this.HasKey(t => t.Id);
// Properties
this.Property(t => t.Name).HasMaxLength(50);
// Table & Column Mappings
this.ToTable("Survey");
this.Property(t => t.Id).HasColumnName("Id");
this.Property(t => t.Name).HasColumnName("Name");
this.Property(t => t.ClientId).HasColumnName("ClientId");
// Relationships
this.HasOptional(t => t.Client)
.WithMany(t => t.Surveys).HasForeignKey(d => d.ClientId);
}
#endregion
}
Entity Framework does exactly what it's told to do. What you've told it is that there is both a one-to-many and a one-to-one relationship between Clients and Surveys. It generated both FKs in the Survey table in order to map both of the relationships that you've requested. It has no idea that you're trying to connect the two relationships together, nor do I think does it have the ability to deal with that.
As an alternative you might want to consider adding a IsDefaultSurvey field on the Survey object so that you can query for the default survey through the Surveys collection that you have on the Client object. You could even go one step further and put it in as a NotMapped property on the Client object so that you could still use Client.DefaultSurvey to get the correct survey, and not have to change any of your other code, as follows:
[NotMapped]
public Survey DefaultSurvey
{
get { return this.Surveys.First(s => s.IsDefaultSurvey); }
}
Please notice that adding the code below you will fix the issue.
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext() : base("DefaultConnection")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Client>()
.HasOptional(x => x.DefaultSurvey)
.WithMany(x => x.Surveys);
.HasForeignKey(p => p.DefaultSurveyID);
{
}
I have a User < Country model. A user belongs to a country, but may not belong to any (null foreign key).
How do I set this up? When I try to insert a user with a null country, it tells me that it cannot be null.
The model is as follows:
public class User{
public int CountryId { get; set; }
public Country Country { get; set; }
}
public class Country{
public List<User> Users {get; set;}
public int CountryId {get; set;}
}
Error: A foreign key value cannot be inserted because a corresponding primary key value does not exist. [ Foreign key constraint name = Country_Users ]"}
You must make your foreign key nullable:
public class User
{
public int Id { get; set; }
public int? CountryId { get; set; }
public virtual Country Country { get; set; }
}
I prefer this (below):
public class User
{
public int Id { get; set; }
public int? CountryId { get; set; }
[ForeignKey("CountryId")]
public virtual Country Country { get; set; }
}
Because EF was creating 2 foreign keys in the database table: CountryId, and CountryId1, but the code above fixed that.
I have the same problem now ,
I have foreign key and i need put it as nullable,
to solve this problem you should put
modelBuilder.Entity<Country>()
.HasMany(c => c.Users)
.WithOptional(c => c.Country)
.HasForeignKey(c => c.CountryId)
.WillCascadeOnDelete(false);
in DBContext class
I am sorry for answer you very late :)
I recommend to read Microsoft guide for use Relationships, Navigation Properties and Foreign Keys in EF Code First, like this picture.
Guide link below:
https://learn.microsoft.com/en-gb/ef/ef6/fundamentals/relationships?redirectedfrom=MSDN