Code-First Entity Framework Custom Id Generated - c#

Is it possible to create generated Id with code-first EF, so basically I want to create Id string with custom format
here is my code, something like this.
public class Customer
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
[DefaultValue("some script maybe")]
public string IdCustomer
{
get
{
return value from attribute script DefaultValue
}
private set {};
}
[DataType(DataType.PhoneNumber)]
[RegularExpression(#"(\()?(\+62|62|0)(\d{2,3})?\)?[ .-]?\d{2,4}[ .-]?\d{2,4}[ .-]?\d{2,4}", ErrorMessage = "Not a valid Phone number")]
public string Custno { get; set; }
[Required(ErrorMessage = "Input is required.")]
public string FirstName { get; set; }
public string LastName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
public string CompanyName { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedDate { get; set; }
public string UpdatedBy { get; set; }
public DateTime UpdatedDate { get; set; }
}
is it possible doing something like that, or any other idea to solved that issue

Related

How to update PostgreSQL database while using .NET 5?

I start to learn .NET 5 to create full-stack applications. I create a model with the following code:
public class Contact
{
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required]
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
[DataType(DataType.PostalCode)]
public int Zip { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
public string Emanil { get; set; }
[DataType(DataType.PhoneNumber)]
public string Phone { get; set; }
// Seting up Date & Time
public DateTime Created { get; set; }
// Seting up using of image
[NotMapped]
[Display(Name = "Image")]
[DataType(DataType.Upload)]
public IFormFile ImageFile { get; set; }
public byte[] ImageData { get; set; }
public string ImageType { get; set; }
// Thinking about primary key that the database will manage
public int Id { get; set; }
// Let's think about a derive property (a combination of firstname & lastname)
[NotMapped]
public string FullName { get { return $"{FirstName} {LastName}"; } }
}
Unfortunately, after creating the app I saw a typo mistake in Email => Emanil.
Now after correcting the typo I try: Add-Migration EmailUpdate but it fails, I do try Update-Database as well still fail, I make corrections on each line were I have Emanil to Email:
public async Task<IActionResult> Create([Bind("FirstName,LastName,Address1,Address2,City,State,Zip,Emanil,Phone,Created,ImageData,ImageType,ImageFile,Id")] Contact contact)
Just want to know the best way to update it (I use Visual Studio for the project).

How to retrive User Information from post ASP.NET CORE MVC

I am developing HelpDesk application using ASP.NET.CORE 5.0 MVC and right now I want to retrive User information from ticket, like UserName,LastName,Email etc
So far I create a little guide using SQL Query
SELECT u.Id as UserId,
u.UserName as Username,
u.Email as UserEmail,
t.UserId as TicetUserId
FROM AspNetUsers u,Tickets t
WHERE u.Id = 2 and t.UserId = 2
So far I want to write this in C# using LINQ and _unitOfWork.
I will try to demostrate my Models starting from basic one which is Ticket.cs
public class Ticket
{
[Key]
public int Id { get; set; }
[Display(Name = "Opis")]
public string Description { get; set; }
[Display(Name = "Kratak Opis")]
[MaxLength(20, ErrorMessage = "Maximalan broj karaktera je 20")]
public string ShortDescription { get; set; }
[Display(Name = "Datum i vrijeme slanja")]
public string DateAndTime { get; set; } = DateTime.Now.ToString("dd/MM/yyyy HH:mm");
//[Display(Name = "Datum i vrijeme zavrsetka")]
//public DateTime Answered { get; set; }
[Display(Name = "Vrsta tiketa")]
public int TicketTypeID { get; set; }
[ForeignKey("TicketTypeID")]
public virtual TicketType TicketType { get; set; }
public int UserId { get; set; }
[ForeignKey("UserId")]
public virtual ApplicationUser ApplicationUser { get; set; }
public int? ClientId { get; set; }
[ForeignKey("ClientId")]
public virtual Client Client { get; set; }
public string Status { get; set; } = TicketStatus.Otvoren.ToString();
}
From TicketModels I have alredy ApplicationUser class and UserId which is ForeignKey to ApplicationUser
And in ApplicationUser.cs I have all property which I need to retrive
public class ApplicationUser : IdentityUser<int>
{
[Required]
[Display(Name = "Ime")]
public string Name { get; set; }
[Required]
[Display(Name = "Adresa")]
public string StreetAddress { get; set; }
[Required]
[Display(Name = "Grad")]
public string City { get; set; }
[Required]
[Display(Name = "Postanski broj")]
public string PostalCode { get; set; }
public int? ClientId { get; set; }
[ForeignKey("ClientId")]
public Client Client { get; set; }
[NotMapped]
public string Role { get; set; }
//[NotMapped]
//public int RoleId { get; set; }
[NotMapped]
public IEnumerable<SelectListItem> RoleList { get; set; }
[NotMapped]
public IEnumerable<SelectListItem> ClientList { get; set; }
}
But basically most property which I need is UserName,EmailAddress.
Is there some way to figure out something like this, since I am begginer in RepositoryPattern and UnitOfWork and it is a little bit confusing me and whatever I try to retrive data I get wroong output.
I try something like:
var userEmail = _unitOfwork.Ticket.GetAll(t => t.Id == ticketId);
This will retrive TicetId which is correct. But how to get TicetId base on UserId ?

Creating a one-to-many relationship EF Core - update-database fail

I wants to create a one-to-many relationship.
The plan is as follows: One Customer can have multiple Bikes. Below I present the data models.
Bike Model
public class Bike
{
[Key]
public Guid Id { get; set; }
[Required]
[MaxLength(50)]
public string Brand { get; set; }
[Required]
public int Size { get; set; }
[Required]
[MaxLength(200)]
public string Description { get; set; }
[Required]
[MaxLength(50)]
public string Model { get; set; }
[ForeignKey("CustomerID")]
public Guid CustomerID { get; set; }
[Required]
[DataType(DataType.DateTime)]
public DateTime AddedBike { get; set; }
}
Customer Model
public class Customer
{
[Key]
public Guid Id { get; set; }
[StringLength(50, MinimumLength = 3)]
[Required]
public string Name { get; set; }
[Required]
[StringLength(50, MinimumLength = 3)]
public string Surname { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[Required]
[DisplayName("Telephone")]
public string TelephoneNumber { get; set; }
[Required]
[DataType(DataType.DateTime)]
public DateTime DateTimeAdd { get; set; }
[DataType(DataType.DateTime)]
[DisplayName("Last Update Customer")]
public DateTime EditDate { get; set; }
public virtual ICollection<Bike> Bike { get; set; }
}
DBContext
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
public DbSet<Bike> Bikes { get; set; }
public DbSet<Customer> Customers { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
Migration is going well. However, update-database causes this error:
PM> update-database
Build started...
Build succeeded.
System.InvalidOperationException: There is no entity type mapped to the table 'Bikes' used in a data operation. Either add the corresponding entity type to the model or specify the column types in the data operation.
...
There is no entity type mapped to the table 'Bikes' used in a data operation. Either add the corresponding entity type to the model or specify the column types in the data operation.
Where is the mistake I am making?
Finally, it worked. I finally deleted all migrations, created a new migration and updated the database.
I then added the relationships in the models, did the migration again and updated the database and it worked.
My models look like this
Bike.cs
public class Bike
{
[Key]
public Guid Id { get; set; }
[Required]
[MaxLength(50)]
public string Brand { get; set; }
[Required]
public int Size { get; set; }
[Required]
[MaxLength(200)]
public string Description { get; set; }
[Required]
[MaxLength(50)]
public string Model { get; set; }
public Guid CustomerID { get; set; }
[Required]
[DataType(DataType.DateTime)]
public DateTime AddedBike { get; set; }
[ForeignKey("CustomerID")]
public Customer Customer { get; set; }
}
Customer.cs
public class Customer
{
[Key]
public Guid Id { get; set; }
[StringLength(50, MinimumLength = 3)]
[Required]
public string Name { get; set; }
[Required]
[StringLength(50, MinimumLength = 3)]
public string Surname { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[Required]
[DisplayName("Telephone")]
public string TelephoneNumber { get; set; }
[Required]
[DataType(DataType.DateTime)]
public DateTime DateTimeAdd { get; set; }
[DataType(DataType.DateTime)]
[DisplayName("Last Update Customer")]
public DateTime Edit { get; set; }
public virtual ICollection<Bike> Bike { get; set; }
}

Creating a view - Order with products

Im not sure how I would do this, I have an Orders class that holds users order details, address etc, and an OrderDetails class that holds the products id's and a Product class that holds all of the product info, cost, colour etc, how would I make a view to hold all of this in one view. Like Order 1 would have OrderDetails 1 and this would hold the products in this order.
For instance I want to display the Order Details, e.g. address, then beneath it the products in this order. How would I go about this? Also it needs to be related to the logged in user
Here are my classes
Order
[Bind(Exclude = "OrderId")]
public partial class Order
{
[ScaffoldColumn(false)]
public int OrderId { get; set; }
[ScaffoldColumn(false)]
public System.DateTime OrderDate { get; set; }
[ScaffoldColumn(false)]
[Remote("CheckUserName", "Account")]
public string Username { get; set; }
[Required]
[StringLength(16, ErrorMessage = "Your name is too long")]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Your last name is required.")]
[StringLength(16, ErrorMessage = "Last name is too long.")]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required(ErrorMessage = "Address is required.")]
public string Address { get; set; }
[Required(ErrorMessage = "City is required.")]
public string City { get; set; }
[Required(ErrorMessage = "Postcode is required.")]
[Display(Name = "Post Code")]
public string PostalCode { get; set; }
[Required(ErrorMessage = "Country is required.")]
public string Country { get; set; }
[Required(ErrorMessage = "Phone number is required.")]
public string Phone { get; set; }
[RegularExpression(#"[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}", ErrorMessage = "Email doesn't look like a valid email address.")]
public string Email { get; set; }
[System.ComponentModel.DataAnnotations.Compare("Email")]
[Display(Name = "Confirm your email address")]
public string EmailConfirm { get; set; }
[ScaffoldColumn(false)]
public string PaymentTransactionId { get; set; }
[ScaffoldColumn(false)]
public bool HasBeenShipped { get; set; }
[ScaffoldColumn(false)]
[ReadOnly(true)]
public decimal Total { get; set; }
public CardDetails cardDetails { get; set; }
//public List<CardDetails> cardDetails { get; set; }
public List<OrderDetail> OrderDetails { get; set; }
Order Details class
public class OrderDetail
{
public int OrderDetailId { get; set; }
public int OrderId { get; set; }
public int ProductId { get; set; }
public int Quantity { get; set; }
public decimal UnitPrice { get; set; }
public virtual Product Product { get; set; }
public virtual Order Order { get; set; }
}
The Product Class
public class Product
{
[Key]
public virtual int ProductId { get; set; }
public virtual int CategoryId { get; set; }
public virtual string Title { get; set; }
public virtual string Description { get; set; }
public virtual string Colour { get; set; }
public virtual string ProductImg { get; set; }
public virtual decimal Price { get; set; }
public virtual int Quantity { get; set; }
public Category Category { get; set; }
}
So the order class would be related to the user, this would show the address etc, then i want the products related to the order beneath it
ViewModel
//From ORDER Table
public int OrderId { get; set; }
public System.DateTime OrderDate { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
public string Email { get; set; }
public decimal Total { get; set; }
//from Products
public List<Product> Products { get; set; }
Use a ViewModel - a class that mediates between the view and the model.
Its very common to need to have view specific data generated outside of the model - combo box items etc, and for this case you should use a View Model. This data is semantically misplaced on the model itself, therefore you use an intermediate object to serve to the view and map this to and from your model classes - you can use a mapper such as AutoMapper to make this process a breeze.
See MVVM:
https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel

Complex relationship mappings in entity framework

I am building a reservation system. I have users in roles('admin', 'client', 'employee', 'student').
Each reservation must be associated with a user of role client, it might be assigned to user of role employee and might also be assigned to user of role student.
So in my reservation class I have properties of type User and I have marked them with [ForeignKey("AnytypeId")] attribute to hint EF for relations.
I have seen code like this at http://blog.stevensanderson.com/2011/01/28/mvcscaffolding-one-to-many-relationships/
public class Reservation
{
public int ReservationID
{
get;
set;
}
[Required(ErrorMessage="Please provide a valid date")]
public DateTime ReservationDate
{
get;
set;
}
public DateTime ReservationEnd { get; set; }
public DateTime EntryDate
{
get;
set;
}
public DateTime UpdatedOn
{
get;
set;
}
public decimal Ammount
{
get;
set;
}
public decimal? Discount { get; set; }
[DataType(DataType.MultilineText)]
public string ServiceDetails { get; set; }
[DataType(DataType.MultilineText)]
public string Remarks { get; set; }
public string VoucherNumber { get; set; }
public int ServiceID
{
get;
set;
}
public Service Service
{
get;
set;
}
public string EmployeeId { get; set; }
[ForeignKey("EmployeeId")]
public User Employee { get; set; }
public string ClientId { get; set; }
[ForeignKey("ClientId")]
public User Client { get; set; }
public string StudentId { get; set; }
[ForeignKey("StudentId")]
public User Student { get; set; }
}
public class User
{
//[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//public Guid UserId { get; set; }
[Key]
[Required(ErrorMessage = "User Name is required")]
[Display(Name = "User Name")]
[MaxLength(100)]
public string UserName { get; set; }
[Required]
[MaxLength(64)]
public byte[] PasswordHash { get; set; }
[Required]
[MaxLength(128)]
public byte[] PasswordSalt { get; set; }
[Required(ErrorMessage = "Email is required")]
[DataType(DataType.EmailAddress)]
[MaxLength(200)]
public string Email { get; set; }
[MaxLength(200)]
public string Comment { get; set; }
[Display(Name = "Approved?")]
public bool IsApproved { get; set; }
[Display(Name = "Crate Date")]
public DateTime DateCreated { get; set; }
[Display(Name = "Last Login Date")]
public DateTime? DateLastLogin { get; set; }
[Display(Name = "Last Activity Date")]
public DateTime? DateLastActivity { get; set; }
[Display(Name = "Last Password Change Date")]
public DateTime DateLastPasswordChange { get; set; }
public string address { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string Phone { get; set; }
public bool? IsActive { get; set; }
public int? ClientTypeID { get; set; }
public virtual ClientType ClientType { get; set; }
public virtual ICollection<Role> Roles { get; set; }
public DateTime? PackageValidity { get; set; }
public virtual ICollection<Reservation> Reservations { get; set; }
}
public class UserMap : EntityTypeConfiguration<User>
{
public UserMap()
{
this.HasMany(u => u.Roles)
.WithMany(r => r.Users)
.Map(m =>
{
m.ToTable("RoleMemberships");
m.MapLeftKey("Username");
m.MapRightKey("RoleName");
});
}
}
Now as I run my mvc3 EF code first app database created for me on the fly with following ERD and edmx model.
Now few problems that I am having:
1. When I am listing all the users of role clients their reservation property is showing always 0 even if their are reservations available in database.
2. If I am trying to delete a user of role client who have reservation in database I get following error.
The DELETE statement conflicted with the REFERENCE constraint "Reservation_Client". The conflict occurred in database "CRSDB", table "dbo.Reservations", column 'ClientId'.
The statement has been terminated.
I checked the realtions in ERD and edmx model their is no cascade delete applied to them. How can I instruct EF to delete all the reservations when deleting user of role client but not for users of role employee or student.
This code does the trick
public class Reservation
{
public int ReservationID
{
get;
set;
}
[Required(ErrorMessage="Please provide a valid date")]
public DateTime ReservationDate
{
get;
set;
}
public DateTime ReservationEnd { get; set; }
public DateTime EntryDate
{
get;
set;
}
public DateTime UpdatedOn
{
get;
set;
}
public decimal Ammount
{
get;
set;
}
public decimal? Discount { get; set; }
[DataType(DataType.MultilineText)]
public string ServiceDetails { get; set; }
[DataType(DataType.MultilineText)]
public string Remarks { get; set; }
public String PaymentMethod { get; set; }
public string VoucherNumber { get; set; }
public int ServiceID
{
get;
set;
}
public virtual Service Service
{
get;
set;
}
public string EmployeeID { get; set; }
[ForeignKey("EmployeeID")]
public virtual User Employee { get; set; }
public string ClientID { get; set; }
[ForeignKey("ClientID")]
public virtual User Client { get; set; }
public string StudentID { get; set; }
[ForeignKey("StudentID")]
public virtual User Student { get; set; }
}
public class ReservationMap : EntityTypeConfiguration<Reservation>
{
public ReservationMap()
{
this.HasOptional(r => r.Client).WithMany().WillCascadeOnDelete(true);
this.HasOptional(r => r.Employee).WithMany().WillCascadeOnDelete(false);
this.HasOptional(r=>r.Student).WithMany().WillCascadeOnDelete(false);
}
}

Categories

Resources