EF Core composite foreign key and constraint - sql

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"));

Related

Link two tables with a one-to-one relationship, using the same unique key

I have two tables that need to be linked one to one by the key field email.
When I try to do this, I get an error like this:
Cannot use table 'UserSettings' for entity type 'UserSettings' since it is being used for entity type 'UserSettings' and potentially other entity types, but there is no linking relationship. Add a foreign key to 'UserSettings' on the primary key properties and pointing to the primary key on another entity type mapped to 'UserSettings'.
how I tried to implement it:
public class UserSettingsConfiguration : IEntityTypeConfiguration<UserSettings>
{
public void Configure(EntityTypeBuilder<UserSettings> builder)
{
builder.HasKey(n => n.Email);
builder.HasOne(n => n.User)
.WithOne(u => u.UserSettings)
.HasForeignKey<UserSettings>(k => k.Email)
.HasPrincipalKey<UserSettings>(k => k.Email);
}
}
UserSettings and User entities:
public class User
{
public string Email { get; set; }
public DateTime RegistrationDate { get; set; }
public string Image { get; set; }
public UserSettings UserSettings { get; set; }
}
public class UserSettings
{
public string Email { get; set; }
public int LanguageId { get; set; }
public User User { get; set; }
}

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 CODE FIRST PRIMARY KEY COMPOSITE KEY PRIMARY KEY

I would like to know if someone knows how to make a table with a primary key composed of two columns, where the first column is sent by me, and the second is generated from the first
public class Person
{
public int idPerson { get; set; }
public string name { get; set; }
}
public class PersonAdress
{
public int idPerson { get; set; }
public int DireccionId { get; set; }
public string reference { get; set; }
}
I am looking for the incremental of the second column to be if the first column changes
how to make a table with a primary key composed of two columns
You can add the following code by fluent api in dbContext's OnModelCreating method :
modelBuilder.Entity<PersonAdress>().HasKey(sc => new { sc.idPerson , sc.DireccionId });
You can also have a reference for this.

Why EF core tries to add navigational property into DB and not only the Id of foreign model?

I was wondering why EF tries to add also foreign models.
Example:
public class Category
{
public int Id { get; set; }
public string Name{ get; set; }
}
public class Content
{
public int Id { get; set; }
public string Name{ get; set; }
public Category Category{ get; set; }
}
After creating "Content" using migrations, I have a table that includes the id of category. That's create. So I have three columns: Id, name and the categoryId. Seems EF "knows" that this should be just the primary key of Category, that needs to get stored.
Than I tried to add something with EF.
var cat = new Category {Id = 2, Name = "awesomeCat"})
var addContent = new Content({Name = "test", Category = cat})
Now I want to add a Content by using _context.Add(addContent). I was expecting a single insert into db that uses the name "test" and the categoryId 2. Id will be generated by DB.
But instead EF also tries to add a new Category into the category table.
So I took a deeper look and seems EF "does" not know it already exists and was not maintaining any transactions about the category model.
I gave it another try and used no new category, instead I was loading it before:
var cat = _context.findById("2");
and assigned this one instead. Now EF should know that this one already exists and does not have to add it in category table.
Could it be, that my model is just wrong.
Do I need to use it more like:
public class Content
{
public int Id { get; set; }
public string Name{ get; set; }
public int? CategoryId{ get; set; }
[ForeignKey("CategoryId")]
public Category Category{ get; set; }
}
Won't I get two category references then?
You need to tell EF Core it's a primary key and to generate the key
public class Category
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
}
public class Content
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public Category Category { get; set; }
}
Then you don't need to mark [ForeignKey("CategoryId")], EF Core will turn the object reference into an ID in the database
If I misunderstood your question, ask again :)
EF Core has internal tracking of entities. When you simply new up a category, it's not being tracked. When you add the content, EF will track any related entities as well, which would include your category, which will by default be tracked as "Added". You have a few choices.
Don't "new up" an existing category, but rather, retrieve it from the database. If EF pulls it from the database, then it will be tracked, and will not be added again.
You can explicitly track the category instance you newed up and set it's state to "Unchanged".
_context.Attach(category);
_context.Entry(category).State = EntityState.Unchanged;
_context.Add(content);
The best method is to not deal with the reference property at all, and use an explicit foreign key property. Add a property to your content class:
public int CategoryId { get; set; }
Then, you can simply set this id, instead of the Category prop:
var addContent = new Content { Name = "test", CategoryId = 2 };
EF will backfill the reference property after save.

Fluent NHibernate one-to-many with intervening join table?

I'm having trouble getting the Fluent Nhibernate Automapper to create what I want. I have two entities, with a one-to-many relationship between them.
class Person
{
public string name;
IList<departments> worksIn;
}
class Department
{
public string name;
}
The above is obviously bare bones, but I would be expecting to generate the fleshed out schema of:
Person{id, name}
Department{id, name}
PersonDepartment{id(FK person), id(Fk Department)}
Unfortunately, I am instead getting:
Person{id, name}
Department{id, name, personid(FK)}
I don't want the FK for Person included on the department table, I want a separate join/lookup table (PersonDepartment above) which contains the primarykeys of both tables as a composite PK and also Fks.
I'm not sure if I am drawing up my initial classes wrong (perhaps should just be LIst workIn - representing ids, rather than List worksIn), or if I need to manually map this?
Can this be done?
The way the classes have been structured suggests a one-to-many relationship (and indeed that's how you describe it in your question), so it should not be a surprise that FNH opts to model the database relationship in that way.
It would be possible, as you suggest, to manually create a many-to-many table mapping. But, is this definitely what you want?
I tend to find that pure many-to-many relationships are quite rare, and there is usually a good case for introducing an intermediate entity and using two one-to-many relationships. This leaves open the possibility of adding extra information to the link (e.g. a person's "primary" department, or perhaps details of their office within each of their departments).
Some example "bare-bones" classes illustrating this kind of structure:
public class Person
{
public int Id { get; set;}
public string Name { get; set;}
public IList<PersonDepartment> Departments { get; set; }
}
public class PersonDepartment
{
public int Id { get; set; }
public Person Person { get; set; }
public Department Department { get; set; }
public bool IsPrimary { get; set; }
public string Office { get; set; }
}
public class Department
{
public int Id { get; set; }
public IList<PersonDepartment> Personnel { get; set; }
public string Name { get; set; }
}