How to set Not Null and Unique key constraint on a property from mvc model - asp.net-mvc-4

How can I apply not null and unique key constraint on a property from asp.net MVC model,
Below is my code:
public class Role
{
public int id { get; set; }
[Required]
[Index("RoelsIndex",IsUnique=true)]
public string Roles { get; set; }
}

Not sure what's your problem but Required and Index work fine when I try it.
public class Product
{
public int Id { get; set; }
[Required]
[Index(IsUnique = true)]
[MaxLength(400)]
public string Name { get; set; }
}
public class AppContext : DbContext
{
public DbSet<Product> Products { get; set; }
}

Related

How to establish one-to-many relationship for a code-first approach?

I'm trying to build a recipe app for my spouse. I'm trying to set it up so she can add new recipes to the database as the app grows.
When adding new recipe, she will have three drop-down to pick from to construct her new recipe ingredients. First one will contain a list of ingredients that she can choose from, the second one a list of measuring units and the third one a list of quantities.
Here is what I got so far. Am I heading in the right direction or am I off? I'm using Entity Framework with a code-first approach:
public class Recipes
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Image { get; set; }
}
public class Units model
{
[Key]
public int Id { get; set; }
public string UnitName { get; set; }
}
public class UnitQty
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
public class IngredientsModel
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
public class RecipeIngredients
{
public int Id { get; set; }
public int RecipesId { get; set; }
[ForeignKey("RecipesId")]
public Recipes Recipes { get; set; }
public int IngredientsModelId { get; set; }
[ForeignKey("IngredientsModelId")]
public IngredientsModel IngredientsModel { get; set; }
public int UnitQtyId { get; set; }
[ForeignKey("UnitQtyId")]
public UnitQty UnitQty { get; set; }
public int UnitsModelId { get; set; }
[ForeignKey("UnitsModelId")]
public UnitsModel UnitsModel { get; set; }
}
After creating the table, controller and the views, this is what I get in the recipe ingredients index view.
Any suggestion will be more than welcome please and thank you
RecipeIngredient class's view
First of all. You are over engineering your domain model. On relational databases Join is bottleneck you should prevent from joins if it doesn't helps you.
public class Recipt
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Image { get; set; }
public ICollection<RecipeIngredient> Ingredients { get; set; }
}
public class IngredientModel
{
public int Id { get; set; }
public string Name { get; set; }
public IngredientUnit UnitType { get; set; } // Unit model is best to be added here. if it doesn't change in a single IngredientModel.
}
public class RecipeIngredient
{
public int Id { get; set; }
public int UnitQuantiy { get; set; } // No need to more classes.
public IngredientModel Model { get; set; }
public Recipt Recipt { get; set; }
}
public Enum IngredientUnitType // Same Unit Model but less database relation as its small finite collection.
{
Killogram,
Count,
....
}
and according to the Microsoft documents its best to use fluentApi configuration for the relations.
Override this method in your Context:
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Recipt>.HasMany(P => P.Ingredients).WithOne(P => P.Recipt);
builder.Entity<RecipeIngredient>.HasOne(P => P.Model);
// There is no need to explicit foreign key definition. but you can explicitly define your foreign keys.
}
And for the last part. in Views you can use extra models called ViewModels.
As above domain turned to a minimal domain you just need to pass a list of IngredientModels to your view to complete your View.

Using database-first approach with string primary key and a one-to-many relationship not working in ASP.NET Core Web API

I have two model classes:
public partial class customer
{
public string customer_id { get; set; } // Primary Key
public string customer_name { get; set; }
public string course_mobile { get; set; }
public List<customer_address> customer_addresses { get; set; }
}
public partial class customer_address
{
public string address_id { get; set; } // Primary Key
public string adreess { get; set; }
public customer customer { get; set; }
public string customer_id { get; set; } // Foreign Key
}
I get an error:
The entity type 'customer' requires a primary key to be defined.
So how it solve?
Datbase table structure
You need to add [Key] attrubute.
public partial class customer
{
[Key]
public string customer_id { get; set; } // Primary Key
public string customer_name { get; set; }
public string course_mobile { get; set; }
public List<customer_address> customer_addresses { get; set; }
}
public partial class customer_address
{
[Key]
public string address_id { get; set; } // Primary Key
public string adreess { get; set; }
public customer customer { get; set; }
public string customer_id { get; set; } // Foriegn Key
}

Is it possible to create a Domain Class which has Multiple FK Columns to same PK?

I'm a newbie to designing database.
I have problem how to define a domain class which has multiple foreign keys linked with a same primary key.
Here is my model:
namespace OceanFmsSystem.Domain
{
public class ExportTemplate
{
public int Id { get; set; }
public List<ExportBooking> ExportBookings { get; set; }
public string TemplateName { get; set; }
public int CustomerId { get; set; }
public string Incoterms { get; set; }
public string IncotermsDetail { get; set; }
public string PaymentTerm{ get; set; }
public int CountryOriginId { get; set; }
public int CountryDestinationId { get; set; }
}
}
What I want to do is that CountryOriginId & CountryDestinationId should refer to the below class as foreign keys:
namespace OceanFmsSystem.Domain
{
public class Country
{
public int Id { get; set; }
public string CountryCode { get; set; }
public string CountryName { get; set; }
}
}
As far as I know, in EF Core there is an convention which I should name a foreign key as below for migration from code to database.
public type ClassNameOfPrimaryKeyId { get; set;}
Is there any possible way to make this happens?
Yes, possible. Your class should look like this:
public class ExportTemplate
{
//...
public int CountryOriginId { get; set; }
public Country CountryOrigin { get; set; }
public int CountryDestinationId { get; set; }
public Country CountryDestination { get; set; }
}
EF is smart enough to figure the Ids by convention. If you do not wish to follow the convention you can use [ForeignKey] attribute on the properties to configure the FK:
[ForeignKey("Origin")]
public int MyOriginId { get; set; }
public Country Origin { get; set; }

Can't see relationship in database diagram entity framework core

I am working on ASP.NET Core application which uses Entity framework core. I am using code first approach to create database model. I am trying the get one-to-many relationship (one user can have multiple products) between following two classes but in database diagram, I can not see that relationship.
public class SystemUser : IdentityUser
{
public SystemUser()
{
this.ProductToUser = new HashSet<ProductsToUser>();
}
[StringLength(200)]
[Required]
public string FullName { get; set; }
[Required]
[StringLength(200)]
public string Address { get; set; }
[Required]
public int PinNo { get; set; }
[Required]
public int StateId { get; set; }
[Required]
public int CountryId { get; set; }
[Required]
public DateTime RegisterDate { get; set; }
public virtual ICollection<ProductsToUser> ProductToUser { get; set; }
}
public class ProductsToUser
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public string UserId { get; set; }
[Required]
public int ProductID { get; set; }
[ForeignKey("UserId")]
public SystemUser SystemUser { get; set; }
}
Below is the screenshot of database diagram.
As you can see in diagram it is not showing relationship. But I am getting foreign key constraint in ProductsToUser table as shown below
How do I resolve this issue?

Entity Relationship - CodeFirst - Multiple Relationships

I'm trying to create the following object for my DB (CodeFirst),
And i have the following problem:
when i try to add new one or many object to a new srevice provider slots (as follows:)
ServiceProviderSlots slot = new ServiceProviderSlots();
slot.ServiceProviderID = 1;
slot.SlotServices.Add(new ServiceProviderServices() { ServiceProviderServiceID = 1 });
ctx.ServiceProviderSlots.Add(slot);
I get an error, because i'm not creating a new object, and i'm missing foreign keys, but i wish to use data which already exists on that table.
ERROR:
{"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_dbo.ServiceProviderServices_dbo.ServiceProviders_ServiceProviderID\". The conflict occurred in database \"qunadodb\", table \"dbo.ServiceProviders\", column 'ServiceProviderID'.\r\nThe statement has been terminated."}
Maybe it's related to this?
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}
Which i used becuase i couldn't create the db otherwise, i had another error.
See below structure:
public class BusinessCategories
{
[Key]
public int CategoryID { get; set; }
public String Title { get; set; }
}
public class BusinessTypes
{
[Key]
public int TypeID { get; set; }
public String Title { get; set; }
public int CategoryID { get; set; }
public virtual BusinessCategories Categories { get; set; }
}
public class ServiceProviders
{
[Key]
public int ServiceProviderID { get; set; }
public String Name { get; set; }
public Int32 TypeID { get; set; }
public virtual BusinessTypes Type { get; set; }
}
public class ServiceProviderServices
{
[Key]
public Int32 ServiceProviderServiceID { get; set; }
public String Price { get; set; }
public Int32 ServiceProviderID { get; set; }
public virtual ServiceProviders ServiceProvider { get; set; }
public Int32 SubServiceID { get; set; }
public virtual SubServices SubService { get; set; }
}
public class ServiceProviderSlots
{
public ServiceProviderSlots()
{
SlotServices = new List<ServiceProviderServices>();
}
[Key]
public Int32 SlotID { get; set; }
public String Name { get; set; }
public Int32 ServiceProviderID { get; set; }
[ForeignKey("ServiceProviderID")]
public virtual ServiceProviders ServiceProvider { get; set; }
public virtual ICollection<ServiceProviderServices> SlotServices { get; set; }
}
this message means that you probably yet have a ServiceProvider with Id = 1 in the database.
in this cas you have to attach the entity to the context.