My table was created in the database. But the primary key I want should be 10 characters long. The primary key must be randomly generated. So it should be a 10-digit random number, not auto-incrementing. How can I do that?
1- The primary key must be 10 characters long. For example: 1674058910
2- The primary key must be randomly generated. It should not be in ascending order.
1- Remove any config for Auto increment like [DatabaseGenerated(DatabaseGeneratedOption.Identity)] attribute.
2 - Create BaseEntity.cs class :
public class BaseEntity
{
public BaseEntity()
{
Id = new Random().Next(1000000000,Int32.MaxValue);
}
public int Id {get; set;}
}
3 - inherit this class in all of you entity like this:
public class User : BaseEntity
{
public string Name {get;set;}
}
4 - Important: you may have a conflict in your id, check the id before insert in the database.
Related
My model has a property defined like this:
public string NameId { get; set; }
I've read that EF recognizes ID if it's names as "ID" or "somethingID". Why it doesn't in my case? It is a primary key in the sql server.
EF is giving correct error.
According to EF design, NameId will be treated as primary key if your class name is Name. Otherwise you have to use [Key] attribute explicitly.
For Example:
public class Entity
{
public string EntityId { get; set; }
}
In the above case EntityId will be regarded as primary key because its prefixed with the class name Entity
I have two "entities", Job Code and Job Family:
public class JobCode{
public int Code {get;set;}
public string Name {get;set;}
}
public class JobFamily{
public int Code {get;set;}
public string Name {get;set;}
}
JobCode.Code is a 5-digit code, and JobFamily.Code is 2 digits, which correspond with the first 2 digits of a Job Code, so there is an intrinsic relationship that I would like to capture in either the code or the database.
If I use code-first Entity Framework (or if I use database-first), is there a way to get something like:
CREATE TABLE JobFamily
(
Code int PRIMARY KEY,
Name varchar(255)
);
CREATE TABLE JobCode
(
Code int PRIMARY KEY,
Name varchar(255),
JobFamily AS (Code / 1000) FOREIGN KEY REFERENCES JobFamily(Code)
);
Is this even possible in SQL Server? I can't find anything saying it's not, but I can't find anyone trying to do it either...
I am having this Entity (both in database and Entity Framework):
public class LanguageValue
{
public int ID { get; set; }
public long Key { get; set; } // bigint in database
public int LanguageID { get; set; } // FK with a Language table in database
public string Value { get; set; } // nvarchar(MAX) in database
public bool Active { get; set; } // bit in database
}
I have already read this article, but my problem is a bit different: EF6: How to generate a unique number automatically based on entity Id
My Key column does not have unique constraint, because there can be multiple rows with the same Key value. For example:
ID Key LanguageID Value
---------------------------------------------------
1 1 1 Name in Language 1
2 1 2 Name in Language 2
I cannot use a Mapping table to enforce a FK instead of Key because multiple tables uses this same table (Product's Name, Category's Name, Article's Content).
Now whenever I need to insert a Product or Category record, I need to insert their corresponding Language Value. However, I have yet to find a way to generate a Key that is unique among them, and more over, need to be unique in case two insert are being processed at once (for example, adding a Product and Category at the same time).
I am thinking about Guid, should that be my safe bet with RNG, or is there any better way/design for achieving it?
OK, I think my problem was from bad database design. I seperated the LanguageValue table into two tables, like the following diagram, and realize 2 pros that the previous design did not have:
I can now safely insert the LanguageKey with IDENTITY.
I can now have FK for Product and Category's NameLanguageKey, which were impossible before because Key was not unique.
Say I have two tables:
Products
[ProductID] PK
[Weight]
[ProductCode]
and
KnownProductCodes
[ProductCode] PK
[Description]
Now I want my Product entity to have a KnownProductCodeDetails property. BUT the interesting thing here is that Products.ProductCode may contain EITHER product codes that DO exist in the KnownProductCodes table, OR the product codes THAT DON'T EXIST in KnownProductCodes table.
So, my question is: how do I create such a relationship between the two entities in Entity Framework?
PS. By the way, is it possible for an entity to have a foreign relationship without having a corresponding constraint in the database?
Thanks!
==
Details: EF 6.1.2, Code first
Such an association wouldn't be a foreign key.
A FK is a contraint, it uses an entity's primary key values to restrict the domain of values in the referencing entity. However, you don't want the values Product.ProductCode to be constrained, so this field can't be a foreign key by definition. (Nor technically).
A second point is that meaningful primary keys, like KnownProductCodes.ProductCode, are nearly always a bad idea, because one day the business may demand to change their values. And changing primary key values is a hassle.
So the obvious thing here would be to create a real nullable foreign key to a new primary key field, KnownProductCodesId. Then you can get the display value for a product's product code either from this FK (if not null) or Product.ProductCode. And modifying KnownProductCodes.ProductCode is easy now.
Another approach could be to create a "free association". Let this be your classes:
public class Product
{
public int ProductID { get; set; }
public decimal? Weight { get; set; }
public string ProductCode { get; set; }
public virtual KnownProductCode KnownProductCode { get; set; }
}
public partial class KnownProductCode
{
public string ProductCode { get; set; }
public string Description { get; set; }
}
Now in the mappings you can define an association between them:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<KnownProductCode>().HasKey(k => k.ProductCode);
modelBuilder.Entity<Product>()
.HasOptional(p => p.KnownProductCode)
.WithMany()
.HasForeignKey(p => p.ProductCode);
}
But in the database you avoid creating the actual FK. EF will allow that, it only wants associations to point to an entity's primary key, but the association doesn't have to be a hard FK in the database.
(Note however that this takes special measures if you create the database from the model, I wouldn't recommend it).
I am using CodeFirst in my project. One of the things I am learning is how I can design my tables by first writing classes. My question is - how can I classify the primary key [key] Id, as an auto increment field. So that when a record is created (or a row in the table) the primary key is auto generated. How do I do this in codefirst while writing class definition. Thanks for the help.
public class NewTable
{
//Looking for something like [AutoIncrement][key] for Id field etc...
[key]
public int Id { get; set; }
[Required(ErrorMessage = "Title is required")]
[DisplayName("Title")]
public string Title { get; set; }
}
A string auto increment? That's not gonna work.
Use int instead, and the PK will be an identity column by default. You don't need the [Key] attribute either; EF will infer that because the property is called Id.