How to create a multi-language enum in EF Core ?
I added French name for enum property in Description attribute. I want to persist these values into the database and use it to show in ASP.NET UI lookup.
How to save/get this value to/from the database when doing EF Core migration?
public enum Level
{
[Description("Basique")]
Basic,
[Description("Standard")]
Standard,
[Description("Prime")]
Premium
}
public class SubscriptionLevel
{
public Level Name { get; set; }
public decimal PricePerMonth { get; set; }
public int NumberOfSimultaneousDevices { get; set; }
}
Thanks in advance .
Related
Consider this simple class, that I will use for one of my Domain objects with EF Core 3.1:
using System;
namespace Blah.Domain
{
public class Response
{
public int Id { get; set; }
public string FullResponseText { get; set; }
public string HttpResponseCode { get; set; }
public string TransactionId { get; set; }
public string TransactionType { get; set; }
public DateTime CreatedDate { get; set; }
}
}
Having a database background, I do not want to use the default type of nvarchar(max) as the column type for string values in my database (SQL Server). How do I specify the column types to be used by EF when creating the table?
Also, do I have to include the whole SYSTEM Namespace just to be able to have the DateTime option available to me for my CreatedDate field or is there another way?
Basically there are two possibilities for this problem. The one is to use the attributes mentioned in the previous answer or to use the fluent API provided by EF core.
Fluent API allows you to configure precisely your database properties.
More info can be found in the documentation
Basically the required code is the following in the database context
modelBuilder.Entity<Address>()
.Property(a => a.StateProvince).HasColumnType("varchar(20)");
You should be able to add an attribute on each string value which will look like this
[MaxLength(50)] //Whatever int value in `maxlength` will be the size in sql
public string FullResponseText { get; set; }
[MaxLength(255)]
public string HttpResponseCode { get; set; }
etc.....
Or you could use [StringLength(50, MinimumLength = 5)]
To use [MaxLength()] you will need System.Collections.Generic. For DateTime System should be the only namespace that you need.
I'm working on mapping a legacy application with classes and use EntityFramework against it.
One flaw I have found in this legacy database is that multiple tables refer to a specific table through 2 different fields.
I'm not sure if this is possible and why I can't seem to find anything about it so I am here.
Here is a visual sample:
public class Term {
[Key]
public string Id { get; set; } // sample value: "12-34-56/78"
public string CleanId { get; set; } // sample value: "12345678" (basically the Id without special characters)
public DateTime Date { get; set; }
}
public class App {
public int Id { get; set; }
public string CleanTermId { get; set; } // foreign key is in Term class using the `CleanId` field
}
public class Question {
public int Id { get; set; }
public string TermId { get; set; } // foreign key is in Term class using the `Id` field
}
How can I properly add a navigational property from App and Question to the Term class using either DataAnnotations (preferred) to Fluent API? I do not require a navigational property from Term to App or Question but it's ok if your answer includes it.
Let me know if this is not clear.
Joining on fields other than Primary Key was something that isnt supported in EF versions prior to EF Core, however with your mention of it being a legacy app I doubt you would want to overhaul it to be able to use EF Core.
There was a User Voice request for the feature to be added Here which the response is that they had no plans to add this functionality into EF6 - so Core would be the only way to really do this.
In terms of your classes you would be able to link Question and Term as its based PK - FK, but the App to Term is basing both on non-PK fields, even with a Unique constraint on the DB, this is something not supported in EF prior to Core
Hi this is the correct Code:
public class Term
{
[Key]
public string Id { get; set; }
public string CleanId { get; set; }
public DateTime Date { get; set; }
}
public class App
{
public int Id { get; set; }
[ForeignKey("CleanTermId")]
public Term MyTerm { get; set; }
public string CleanTermId { get; set; }
}
public class Question
{
public int Id { get; set; }
[ForeignKey("TermId")]
public Term MyTerm { get; set; }
public string TermId { get; set; }
}
My database entity project has count about 30 columns, I would like to create clear EF Core model which many of them is grouped in several classes.
For example, overriding entity is Sensors and it has two elements (Int ID, ElectricalData electricalData), ElectricalData is a seperate class which has next 3 seperate classes and two bool and string objects.
A model constructed in this way in Add-Migration process returns feedback that sub-entities doesn't have a primary key, but they shouldn't contain PK, because only Sensors class should have a primary key.
How can I solve this problem? Does this idea is correct?
Code below:
public class SensorModel
{
[Key]
public int ID { get; set; }
public ElectricalDataModel ElectricalData { get; set; }
}
public class ElectricalDataModel
{
public TensionModel Tension { get; set; }
public CurrentModel Current { get; set; }
public string SecurityClass { get; set; }
public ResistanceModel Resistance { get; set; }
public bool ReversePolarizationSecurity { get; set; }
}
public class TensionModel
{
public double Minimum { get; set; }
public double Maximum { get; set; }
public string Current { get; set; }
}
//.......................................... and so on
What are you asking was called Complex Types, and the EF Core term is Owned Entity Types. By default they share the same table as the owner and are used to just logically separate (group) the related properties - exactly the goal you are describing.
The easiest way to identify a class as owned type in EF Core 2.1 is to mark it with OwnedAttribute:
[Owned]
public class ElectricalDataModel
{
// Properties..
}
[Owned]
public class TensionModel
{
// Properties..
}
//.......................................... and so on
Of course the same can be achieved via the OwnsOne fluent API, which also allows you to configure the column names and other attributes for the owned entity per owner.
I want to create an 1:n relationship, based on the naming conventions for creating relationships, with the Entity Framework. I'm using codefirst. Entity Framework ignores the conventions and alwas creates two foreign key columns, instead of only one:
StreamWorkerUser_Id (i want only this column)
StreamWorkerUser_Id1
The configuration class is configured like following:
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
I'm using the Microsoft.Identity Framework, with custom classes for all models.
My DbContext class is as simple as following.
public class StreamWorkerDataContext : IdentityDbContext<StreamWorkerUser, StreamWorkerRole, int, StreamWorkerUserLogin, StreamWorkerUserRole, StreamWorkerUserClaim>
{
public DbSet<Task> Tasks { get; set; }
}
The Task model:
public class Task : StreamWorkerEntity
{
public StreamWorkerUser StreamWorkerUser { get; set; }
}
The StreamWorkerUser model:
public class StreamWorkerUser : IdentityUser<int, StreamWorkerUserLogin, StreamWorkerUserRole, StreamWorkerUserClaim>
{
public virtual List<Task> Tasks { get; set; } // also tested ICollection
}
The Task class inherits from this base type, here are also two properties of type StreamWorkerUser defined (But these columns generated correctly in the database.):
public class StreamWorkerEntity
{
[Key]
public int Id { get; set; }
public DateTimeOffset Created { get; set; }
public DateTimeOffset Updated { get; set; }
public StreamWorkerUser Creator { get; set; }
public StreamWorkerUser LastEditor { get; set; }
}
Is it possible that, the properties Creator and LastEditor disturbing the database migration?
Do i understand the conventions correctly?
Much more information:
Entity Framework Version 6.1.3
Microsoft.AspNet.Identity.Core 2.2.1
Microsoft.AspNet.Identity.EntityFramework 2.2.1
ASP.NET 4 MVC 5
SQL Server in Azure Cloud
C# 6.0
.NET Framework 4.5.2
All of this code is in a class libary
So you might think that EF in this situation:
public StreamWorkerUser Creator { get; set; }
public StreamWorkerUser LastEditor { get; set; }
will create creator_id and lasteditor_id, but it doesn't, because EF took class name and made StreamWorkerUser_Id, and StreamWorkerUser_Id1, because there were StreamWorkerUser_Id already used. By default, if you make relation by class(not by int field), EF generates its column name depending on the class name(not by field name).
If you want to specify column names for those FK you can do :
public int CreatorId { get; set; } //this field name will be column name
[ForeignKey("StreamWorkerUser")]
public StreamWorkerUser Creator { get; set; }
public int EditorId { get; set; } //this field name will also be column name
[ForeignKey("StreamWorkerUser")]
public StreamWorkerUser Editor { get; set; }
Is there an attribute I can use when creating a table ? I tried [StringLength] but it seems to be ignored.
public class EntityRegister
{
public int Id { get; set; }
[StringLength(450)]
public string Name { get; set; }
}
alternatively, you can manually do it on Fluent API
use HasMaxLength(450)
Configuring Properties and Types with the Fluent API
EF 6
EF Core
or if you want Data Annotation, use MaxLength and MinLength attributes
public class EntityRegister
{
public int Id { get; set; }
[MaxLength(450)]
public string Name { get; set; }
}
Code First Data Annotations