How to use data annotation with SQL views? MVC & EF6 - entity-framework-6

My database contains both tables and views. I can use "Data annotation" with tables :), but I failed with Views:(.
I use meta data classes to apply data annotation on the EF generated classes.
class V_TasksList_MD
{
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> SubmitDate { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public System.DateTime StartDate { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public System.DateTime DueDate { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> ProgressDate { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> CompleteDate { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> ApproveDate { get; set; }
}
[MetadataType(typeof(V_TasksList_MD))]
public partial class V_TasksList
{
}

Related

ASP.NET date range constraint/validation

If I have a model that tracks employees request for holidays, how would I go about ensuring that an employee does not take multiple holidays within the same date range? Would this be handled with validation or creating a constraint in SQL Server? I used database first for this project.
public partial class HolidayRequestForm
{
public int RequestID { get; set; }
public int EmployeeID { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yy}", ApplyFormatInEditMode = true)]
public System.DateTime StartDate { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yy}", ApplyFormatInEditMode = true)]
public System.DateTime FinishDate { get; set; }
[Range(0.0001, int.MaxValue, ErrorMessage = "Hours Requested must be greater than zero. ")]
public decimal HoursTaken { get; set; }
public string Comments { get; set; }
public int YearCreated { get; set; }
public int MonthCreated { get; set; }
public int DayCreated { get; set; }
public Nullable<int> YearOfHoliday { get; set; }
[UIHint("Boolean.cshtml")]
public Nullable<bool> Approved { get; set; }
public string SubmittedBy { get; set; }
public string ApprovedBy { get; set; }
public virtual Employee Employee { get; set; }
}
Ideally I'd like that two employees can request the same date range but a single employee cannot request two holidays within the same date range. Could I use custom validation attribute maybe??
The given scenario is a business logic so it is better to implement this in your code itself instead of database constrains or triggers.
You can create a custom validator for the same and do a validation in the business layer. This approach will be easy maintainable/upgradable.
Use a normal method for validation , or create custom ValidationAttribute by inhering ValidationAttribute and by overriding IsValid method.

A specified Include path is not valid on eager loading

I am using eager loading in entity framework. My Model class is like
public class EmployeeMaster : AbsCommonParameters
{
[Key]
public int Id { get; set; }
public string EmpId { get; set; }
[Required(ErrorMessage = "Employee name is required")]
public string Name { get; set; }
[Required(ErrorMessage = "Employee geography is required")]
public string Geography { get; set; }
public string EmailId { get; set; }
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
[Column(TypeName = "Date")]
[Display(Name = "Date Of Joining")]
public Nullable<DateTime> DOJ { get; set; }
[Required(ErrorMessage = "Employee designation is required")]
public string Designation { get; set; }
[NotMapped]
public List<CenterMaster> lstCenters { get; set; }
[NotMapped]
public List<CostCodeMaster> lstCostCode { get; set; }
}
In Controller Index Action my Code is like this
public ActionResult Index()
{
var lstUser = db.ObjEmployeeMaster.Include(p => p.lstCenters).
Include(p => p.lstCostCode).Where(x => x.DeletedStatus == false).ToList();
return View(lstUser);
}
Also In DBContext Constructor I have used
this.Configuration.LazyLoadingEnabled = false;
After this I got error
A specified Include path is not valid
Please help where I am wrong.
Thanks in advance.

Many to many relationship in MVC - write to a table with foreign keys

In model I have 3 tables in relation to many many.
public class Order
{
[Key]
public int IdOrder { get; set; }
public string UserId { get; set; }
public virtual User User { get; set; }
public int IdOrderAttachment { get; set; }
public virtual OrderAttachment OrderAttachment { get; set; }
public virtual ICollection<Employee> Employee { get; set; }
[Required(ErrorMessage = "Specify the date of order acceptance")]
[Display(Name = "Date of acceptance of the order")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTimeDateOfAcceptance { get; set; }
[Display(Name = "Date of completion planning")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? DateOfCompletionPlanning { get; set; }
[Display(Name = "End Date")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? EndDate { get; set; }
[Required(ErrorMessage = "Enter the subject")]
[MaxLength(200, ErrorMessage = "Name max 200 characters")]
[Display(Name = "Subject")]
public string Subject { get; set; }
public virtual ICollection<OrderPosition> OrderPosition{ get; set; }
}
public class OrderPosition
{
[Key]
public int IdOrderPosition { get; set; }
public int IdOrder { get; set; }
public int IdPosition { get; set; }
public virtual Order Order { get; set; }
public virtual Position Position { get; set; }
}
public class Position
{
[Key]
public int IdPosition { get; set; }
[Column(TypeName = "nvarchar(MAX)")]
[Display(Name = "Description")]
[UIHint("tinymce_jquery_full"), AllowHtml]
public string Description { get; set; }
public virtual ICollection<OrderPosition> OrderPosition { get; set; }
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateOrder(HttpPostedFileBase file, DataOrderUserViewModel viewModel)
{
var userId = User.Identity.GetUserId();
if (ModelState.IsValid)
{
if (file != null && file.ContentLength > 0)
{
string path = "/Content/Layout/CompanyFile";
if (!Directory.Exists(HttpContext.Server.MapPath(path)))
{
Directory.CreateDirectory(HttpContext.Server.MapPath(path));
}
string filename = Path.GetFileName(file.FileName);
file.SaveAs(Path.Combine(HttpContext.Server.MapPath(path), filename));
viewModel.NameFile = path+ "/" + filename;
//var nameFile = Path.GetFileName(file.FileName);
//var path = Path.Combine(Server.MapPath("/Content/Layout/CompanyFile"), nameFile);
//file.SaveAs(path);
}
var order = new Order()
{
DateTimeDateOfAcceptance = viewModel.DateTimeDateOfAcceptance,
Subject= viewModel.Subject,
UserId = userId
};
var position = new Position ()
{
Description = viewModel.Description
};
var orderAttachment = new OrderAttachment ()
{
NameFile= viewModel.NameFile,
Description = viewModel.Description2
};
db.Order.Add(order);
db.Position.Add(position);
db.OrderAttachment.Add(orderAttachment);
db.SaveChanges();
}
return RedirectToAction("Index", "Administration");
}
My question is how to write data to the OrderPosition table.
I understand that I should first write data in the Order and Position table.
Then, having two keys from these arrays, I should read them and send them to the OrderPosition as external keys where they will be saved.
What should a record of these instructions look like?
Do I need to define the following relationships in my case?
modelBuilder.Entity<OrderPosition>()
.HasKey(c => new { c.IdOrder , c.IdPosition });
modelBuilder.Entity<Order>()
.HasMany(c => c.Subject )
.WithRequired()
.HasForeignKey(c => c.IdOrder );
modelBuilder.Entity<Position>()
.HasMany(c => c.Description )
.WithRequired()
.HasForeignKey(c => c.IdPosition );

MVC Entity Framework Models and Relationships

im quite new to ASP.net and entity framework. I created a class but im just going to simplify it and take the example class from Microsoft. So here we go. These are all the example classes
public class Student
{
public int ID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime EnrollmentDate { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
public class Instructor
{
public int ID { get; set; }
[Required]
[Display(Name = "Last Name")]
[StringLength(50)]
public string LastName { get; set; }
[Required]
[Column("FirstName")]
[Display(Name = "First Name")]
[StringLength(50)]
public string FirstMidName { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Hire Date")]
public DateTime HireDate { get; set; }
[Display(Name = "Full Name")]
public string FullName
{
get { return LastName + ", " + FirstMidName; }
}
public virtual ICollection<Course> Courses { get; set; }
public virtual OfficeAssignment OfficeAssignment { get; set; }
}
public class OfficeAssignment
{
[Key]
[ForeignKey("Instructor")]
public int InstructorID { get; set; }
[StringLength(50)]
[Display(Name = "Office Location")]
public string Location { get; set; }
public virtual Instructor Instructor { get; set; }
}
public class Course
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[Display(Name = "Number")]
public int CourseID { get; set; }
[StringLength(50, MinimumLength = 3)]
public string Title { get; set; }
[Range(0, 5)]
public int Credits { get; set; }
public int DepartmentID { get; set; }
public virtual Department Department { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
public virtual ICollection<Instructor> Instructors { get; set; }
}
Like i said this is just for a example im trying to get know it.
My First Question: Do you need something like DepartmentID When you already do public virtual Department Department?
Second question: When i have a Collection of data how do i add values or Ids to that collection in the controller i can find this anywhere.
Third Question: Can some one link me a complete MVC example application with proper relationships

How to display a currency format in MVC

In the model class, I am trying to display a currency format for the "Price" field, however the code I am using is not producing the desired result, and I have no idea why it is not working. I do not want to hard code the $ on every page, that would be a hassle. Here is the code I have in the model.
public partial class Item
{
public int ItemId { get; set; }
public string ItemDescription { get; set; }
public Nullable<int> Quantity { get; set; }
[DisplayName("Price Each")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:c}")]
public string Price { get; set; }
[DisplayName("Due Date")]
[DisplayFormat(DataFormatString ="{0:d}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> DueDate { get; set; }
[DisplayName("Date Received")]
[DisplayFormat(DataFormatString= "{0:d}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> DateReceived { get; set; }
public string Comments { get; set; }
[DisplayName("W/O# or Cost Center")]
public int PurchaseID { get; set; }
public virtual PurchaseOrder PurchaseOrder { get; set; }
}
Thanks.
Wrong property type.
try:
public decimal Price { get; set; }

Resources