Create a hierarchical foreign key to Identity 3 ApplicationUser:IdentityUser - asp.net-core

I am using Identity 3 in ASP.NET 5 RC1/Core
I need to create a foreign key reference in the ApplicationUser that refers to the primary key of the ApplicationUser(IdentityUser) using EF Code First.
I have tried
public class ApplicationUser : IdentityUser
{
[Column("fk_LineManagerUserId")]
public Guid LineManagerUserId { get; set; }
[ForeignKey("LineManagerUserId")]
public virtual ApplicationUser LineManagerUser { get; set; }
}
or
public class ApplicationUser : IdentityUser
{
[Column("fk_LineManagerUserId")]
public string LineManagerUserId { get; set; }
[ForeignKey("LineManagerUserId")]
public virtual ApplicationUser LineManagerUser { get; set; }
}
but I get
Introducing FOREIGN KEY constraint 'FK_ApplicationUser_ApplicationUser_LineManagerUserId' on table 'AspNetUs
ers' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

Related

EF Core composite foreign key and constraint

In my project I have noticed that I will be have a lot of dictionaries with the same structure:
shortcut
full name for tooltip
which will be used on many different business forms.
I started to thing that there is no sense to keep all of them in separate tables.
It is better to keep all of them in one table and provide an additional column (DictionaryType) which will separate them in the case of asking the database for data?
So one repository with such method
public class DictionaryEntity
{
public Guid Id { get; set; }
public string Name { get; set; }
public string FullName { get; set; }
public DictionaryType Type { get; set; }
}
public async Task<IEnumerable<DictionaryEntity> GetDictionaries(DictionaryType type)
{
return await _dbContext.Dictionaries.Where(d => d.DictionaryType == type).ToArrayAsync();
}
If new dictionaries appear, I need to only extend DictionaryType and I don't need to worry about database changes or repo/service/controller changes.
For now it is nice and easy, but... I would like to configure foreign key in business entities in that way:
public class CarEntity
{
public Guid Id { get; set; }
public Guid ModelTypeId { get; set;}
public DictionaryEntity ModelType { get; set;}
public Guid PetrolTypeId { get; set;}
public DictionaryEntity PetrolType { get; set;}
}
How to configure in EF Core, foreign key in that way where:
CarEntity.ModelTypeId points to DictionaryEntity.Id and DictionaryEntity.Type = DctionaryType.ModelType ?
CarEntity.PetrolTypeId points to DictionaryEntity.Id and DictionaryEntity.Type = DctionaryType.PetrolType ?
I read, that there is something like a composite foreign key, so I could do FK on { dict.Name, dict.Type } but it demands from me to keep in CarEntity as many properties as composite foreign key have.
Is there a chance to do unique constraint across multiple tables ?
Something like this:
modelBuilder.Entity<CarEntity>()
.HasCheckConstraint("CK_ModelType", "[ModelTypeId] IS NOT NULL AND [Document].[Type] = 'ModelType'", c => c.HasName("CK_ModelType_Dictionary"));

Asp.net core Add Soft delete by modelBuilder.Entity<DependenciaDisciplina>().Property<bool>("isDeleted"); but isDeleted as composite key

I insert the soft delete flag with
modelBuilder.Entity<DependenciaDisciplina>().Property<bool>("isDeleted");
But i need to add it as a composite key
Can somebody help me?
I insert the soft delete flag with
modelBuilder.Entity<DependenciaDisciplina>().Property<bool>("isDeleted");
But i need to add it as a composite key
To set the Composite Keys using the Fluent API, we have to use the HasKey() method.
After check the HasKey() method definition, we can see that the parameter should be a string array or an expression.
So, you could use the set the composite key like this (change the Car model to your model):
modelBuilder.Entity<Car>().Property<bool>("isDeleted");
modelBuilder.Entity<Car>().HasKey(new string[] { "CarId", "isDeleted" });
The Car model:
public class Car
{
[Key]
public int CarId { get; set; }
public string CarName { get; set; }
public string LicensePlate { get; set; }
public string Make { get; set; }
public string Model { get; set; }
}
Then, after migration, the result like this:

EF Core - create relation between two models without a foreign key constaint

I'm working on a microservice system where I replicate Users and Tokens across multiple services.
Sometimes, Token is received before User that it belongs to and I get an error:
MessageText: insert or update on table "Tokens" violates foreign key constraint "FK_Tokens_User_UserId"
Detail: Key (UserId)=(12) is not present in table "User".
Is there a way in EFCore to have relations with navigational properties, but without the constraint - so I can add Token with a not-yet-existing Id as foreign key, that'll eventually be consistent?
Here's the models:
Token:
public class Token
{
public long Id { get; set; }
public long? UserId { get; set; }
public virtual User User { get; set; }
}
User:
public class User
{
public long Id { get; set; }
public virtual ICollection<Token> Tokens { get; set; }
}
Here's the portion of migration.designer.cs generating foreign key:
modelBuilder.Entity("Vehicloo.NoticeboardService.Database.Models.Token", b =>
{
b.HasOne("Vehicloo.NoticeboardService.Database.Models.User", "User")
.WithMany("Tokens")
.HasForeignKey("UserId");
b.Navigation("User");
});
Just remove line:
public virtual ICollection<Token> Tokens { get; set; }
from User and this line:
public virtual User User { get; set; }
from Token. This tells EF not create any foreign key for the User-Token. Consequently, you will have the UserId column in the Token table without any constraint.
For queries, you can join two table manually.

Foreign key may cause cycles or multiple cascade paths entity framework core

I am using Entity Framework core and I added a model called CourseOffering to my project. This model is related to other classes like Section. I successfully created a migration for it. The problem is when I try to apply the migration to the database. I get the following error:
Introducing FOREIGN KEY constraint 'FK_CourseOfferings_Sections_SectionId' on table 'CourseOfferings' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint or index. See previous errors.
I was trying to turn off cascade delete with FluentAPI, but I'm not entirely sure if that is the right solution to my problem. I mean is this totally safe to turn off cascade delete?
My CourseOffering model:
public class CourseOffering
{
public int Id { get; set; }
public Section Section { get; set; }
public Instructor Instructor { get; set; }
public Course Course { get; set; }
public AcademicSemester AcademicSemester { get; set; }
public int SectionId { get; set; }
public int InstructorId { get; set; }
public int? CourseId { get; set; }
public int AcademicSemesterId { get; set; }
}
My Section Model:
public class Section
{
public int Id { get; set; }
[Required]
[StringLength(10)]
public string Name { get; set; }
public int EntranceYear { get; set; }
public int StudentCount { get; set; }
public Department Department { get; set; }
public ProgramType Program { get; set; }
public AdmissionLevel AdmissionLevel { get; set; }
public ICollection<RoomSectionAssignment> RoomAssignments { get; set; }
public int DepartmentId { get; set; }
public int ProgramTypeId { get; set; }
public int AdmissionLevelId { get; set; }
public Section()
{
RoomAssignments = new Collection<RoomSectionAssignment>();
}
}
The migration created all the necessary foreign keys but there is cascade path that would cause cycles. I am not able to figure out what caused the cycle. Should I just turn off cascade delete with FluentAPI?
I was trying to turn off cascade delete with FluentAPI, but I'm not entirely sure if that is the right solution to my problem. I mean is this totally safe to turn off cascade delete?
Yes! This is the appropriate solution in this case! Moreover yes! This is completely safe to turn off cascade delete using FluentAPI because FluentAPIwill generate constraint on database too.

Duplicated reference key - Fluent NHibernate Automapping

I got a problem with automapping in fluent and reference key. Example would be that:
public class ConfigurationCategory
{
public virtual Guid Id { get; private set; }
[NotNull]
public virtual String Name { get; set; }
public virtual String Description { get; set; }
public virtual String Icon { get; set; }
public virtual ConfigurationCategory Parent { get; set; }
public virtual IList<ConfigurationCategory> Children { get; private set; }
public ConfigurationCategory()
{
Children = new List<ConfigurationCategory>();
}
}
Results in the following SQL-Output:
CREATE TABLE "ConfigurationCategory"
...
parent_id uuid,
configurationcategory_id uuid,
CONSTRAINT "ConfigurationCategory_pkey" PRIMARY KEY (id),
CONSTRAINT fk6ccc850055890dc8 FOREIGN KEY (configurationcategory_id)
REFERENCES "ConfigurationCategory" (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT fk6ccc8500ee71b726 FOREIGN KEY (parent_id)
REFERENCES "ConfigurationCategory" (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
Why is ConfigurationCategory duplicated?
I haven't used fluent automapping, but I would guess it is confused by the fact that you have both the Parent and the Children properties; I would guess fluent can't tell that they are both meant to be handled by the same column in the database.
You probably need to create a ClassMap and specify the key column names for both the References() and HasMany() calls.