Entities with problems and limitations - sql-server

I have these entities:
public class Project : Base
{
public string Name { get; set; }
public string Description { get; set; }
public DateTime StartDate { get; set; }
public DateTime? EndDate { get; set; }
public ProjectStatus CurrentStatus { get; set; } = ProjectStatus.New;
public List<StatusHistory>? StatusHistories { get; set; }
public Team? Team { get; set; }
public int? TeamId { get; set; }
// public ProgressTrackerValue trackerValue { get; set; }
public List<AttachedFile> AttachedFiles { get; set; }
}
public class Task : Base
{
public string Name { get; set; }
public string Description { get; set; }
public DateTime? EstimatedDueDate { get; set; }
public DateTime? ActualDueDate { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; } // ?? End DATE same as ActualDueDate
public TaskStatus CurrentStatus { get; set; } = TaskStatus.Draft;
public int ProjectId { get; set; }
public Project Project { get; set; }
public List<StatusHistory> StatusHistories { get; set; }
public TaskType TaskType { get; set; }
public TaskPriority Priority { get; set; }
public float ? DurationProgress { get; set; }
public List<AttachedFile> AttachedFiles { get; set; }
}
public class Team : Base
{
public string TeamLeaderId { get; set; }
public List<TeamMember>? TeamMembers { get; set; }
public virtual Project Project { get; set; }
}
public class AttachedFile : Base
{
public string OriginalFileName { get; set; }
public string FileName { get; set; }
public string MimeType { get; set; }
public string FileType { get; set; }
public string OwnerType { get; set; }
public int OwnerId {get; set;}
public string FilePath { get; set; }
public long FileSize { get; set; }
}
public class Comment : Base
{
public string Content { get; set; }
public int? ParentCommentId { get; set; }
public List<Comment>? Replies { get; private set; }
public Task Task { get; set; }
public int taskId { get; set; }
public List<AttachedFile>? AttachedFiles { get; set; }
}
public class StatusHistory : Base
{
public string OwnerType { get; set; }
public int OwnerId {get; set;}
public string State { get; set; }
}
public class TaskEmployee : Base
{
public int TaskId { get; set; }
public Task Task { get; set; }
public string EmployeeId { get; set; }
}
public class TeamMember : Base
{
public string UserId { get; set; }
}
What can I do to improve the above entities? Any suggestions.
Also there is UserId,EmployeeId,TeamLeaderId.... all of these supposed to be FK to IdentityUser but this project is isolated from Identity and i can't find a way to link them together. if there is a suggestion on how could I make such relationship in EFCore. (I could make relationship manually but I can't put navigation properties for Identity inside these entities thus not benefiting from EFCore).
Finally there is OwnerType, OwnerId, for example in the AttachedFile entity the attached file could be related to Project, Task, Comment. So I will store the type and id for them in these fields, the problem however that I will not benefit form EF Core functionality this way. For example: I must write SQL manually for every query.
currently the schema look like this:
enter image description here

Related

Cannot get my database-update to work

I have launched my website in beta-version. The next version should contain a shopping cart and a checkout with the credit card. On my way to making this shopping cart, I've discovered that my old Product-class with several different prices simply doesn't work. I need one price with one identity or a subclass with several prices mapped to the original class(which I will use) :
public class Product
{
[Key]
public int ProductID { get; set; }
[Required(ErrorMessage = "Please enter an product name")]
public string Name { get; set; }
[Required(ErrorMessage = "Please specify a category")]
public string Category { get; set; }
public string SubCategory { get; set; }
public string Description { get; set; }
public decimal Price16 { get; set; }
public decimal Price12 { get; set; }
public decimal Price8 { get; set; }
public decimal Price4 { get; set; }
public decimal PriceEach { get; set; }
public decimal PriceKg { get; set; }
public string ProductImageSmallUrl { get; set; }
public string ProductImageSmallAlternativeDescription { get; set; }
public string ProductImageSmallContentType { get; set; }
public string ProductImageLargeUrl { get; set; }
public string ProductImageLargeAlternativeDescription { get; set; }
public string ProductImageLargeContentType { get; set; }
public string ProductImageLargeSecondUrl { get; set; }
public string ProductImageLargeSecondAlternativeDescription { get;
set; }
public string ProductImageLargeSecondContentType { get; set; }
}
I have after, a lot of research constructed two classes:
public class Product
{
public Product(ICollection<Price> prices)
{
Prices = prices;
}
[Key]
public int ProductID { get; set; }
[Required(ErrorMessage = "Please enter an product name")]
public string Name { get; set; }
[Required(ErrorMessage = "Please specify a category")]
public string Category { get; set; }
public string SubCategory { get; set; }
public string Description { get; set; }
public string ProductImageSmallUrl { get; set; }
public string ProductImageSmallAlternativeDescription { get; set; }
public string ProductImageSmallContentType { get; set; }
public string ProductImageLargeUrl { get; set; }
public string ProductImageLargeAlternativeDescription { get; set; }
public string ProductImageLargeContentType { get; set; }
public string ProductImageLargeSecondUrl { get; set; }
public string ProductImageLargeSecondAlternativeDescription { get;
set; }
public string ProductImageLargeSecondContentType { get; set; }
public ICollection<Price> Prices { get; set; }
}
And a price class:
public class Price
{
[Key]
public int ID { get; set; }
public int CurrentProductID { get; set; }
public string Size { get; set; }
public decimal Value { get; set; }
public Product CurrentProduct { get; set; }
}
I have this DbContext:
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<MokaMokkaDbContext>
options)
:base(options) {}
public DbSet<Product> Products { get; set; }
public DbSet<Price> Prices { get; set; }
protected override void OnModelCreating (ModelBuilder modelBuilder)
{
modelBuilder.Entity<Price>()
.HasOne(p => p.CurrentProduct)
.WithMany(b => b.Prices)
.HasForeignKey(p => p.CurrentProductID);
}
}
I am trying to write a seeding class:
public class SeedData
{
public static EnsurePopulated(IApplicationBuilder app)
{
MokaMokkaDbContext context = app.ApplicationServices
.GetRequiredService<MokaMokkaDbContext>();
context.Database.Migrate();
if(!context.Products.Any())
{
context.Products.AddRange(
new Product
{
Name = "Dobos cake",
Category = "Cake",
ProductImageSmallUrl = "Dobos.Torta.jpg",
ProductImageSmallContentType = "jpg",
Prices = new List<Price>()
});
}
}
But I get the following problem in over the red underline of the Product I am trying to create: "There is no argument given that corresponds to the required formal parameter "prices" of Product.Product(ICollection)".
I believe you need parameterless constructor in your Product class.

how to combine multiple models into one viewmodel based on a condition ? (WPF)

I have the following three models:
namespace Company.Model {
class Country
{
public int CountryId { get; set; }
public string CountryName { get; set; }
} }
and
namespace Company.Model
{
class Employee
{
public int EmployeeId { get; set; }
public string EmployeeFirstName { get; set; }
public string EmployeeMiddleName { get; set; }
public string EmployeeLastName { get; set; }
public DateTime? EmployeeDOB { get; set; }
public char? EmployeeGender { get; set; }
public string EmployeeAddress { get; set; }
public int? EmployeeContactNumber { get; set; }
public string EmployeeEmailID { get; set; }
public DateTime? EmployeeJoiningDate { get; set; }
public DateTime? EmployeeConfirmationDate { get; set; }
public DateTime? EmployeeExpectedInTime { get; set; }
public DateTime? EmployeeExpectedOutTime { get; set; }
public bool? EmployeeIsResigned { get; set; }
public double? EmployeeSalary { get; set; }
public string EmployeeDesignation { get; set; }
public int? DepartmentId { get; set; }
public int? CountryId { get; set; }
}
}
and
namespace Company.Model
{
class Department
{
public int DepartmentId { get; set; }
public string DepartmentName { get; set; }
}
}
Now I need to combine all three into one viewmodel, based on the condition that Employee.CountryId=Country.CountrId and Employee.DepartmentId=Department.DepartmentId.
I basically want a join on the tables, so as to get country name and department name of each employee.

Invalid object name 'dbo.customers1'

I'm getting the error "Invalid object name 'dbo.customers1'" on my view...
#foreach (var item in Model)
{
<tr>
<td>#item.orderid</td>
<td>#item.customer.firstname</td>
I have the ViewModel classes...
public class orders
{
[Key]
public int orderid { get; set; }
public System.DateTime createdate { get; set; }
public string createdby { get; set; }
public Nullable<int> statusid { get; set; }
public Nullable<System.DateTime> pickup { get; set; }
public Nullable<System.DateTime> dropoff { get; set; }
public Nullable<System.DateTime> scheduledout { get; set; }
public Nullable<System.DateTime> scheduledin { get; set; }
public bool instorepickup { get; set; }
public string paymenttype { get; set; }
public System.DateTime reservationstart { get; set; }
public System.DateTime reservationend { get; set; }
public bool morningpickup { get; set; }
public Nullable<int> customerid { get; set; }
public string notes { get; set; }
public string shippingtype { get; set; }
public Nullable<decimal> shippingestimate { get; set; }
public virtual customer customer { get; set; }
public virtual ICollection<invoice> invoices { get; set; }
public virtual orderstatuses orderstatuses { get; set; }
public virtual ICollection<serialorders> serialorders { get; set; }
}
and
public class customers
{
[Key]
public int customerid { get; set; }
public System.DateTime createdate { get; set; }
public string firstname { get; set; }
public string lastname { get; set; }
[Required]
public string billingaddress1 { get; set; }
public string billingaddress2 { get; set; }
[Required]
public string billingcity { get; set; }
public string billingstate { get; set; }
[Required]
public string billingzip { get; set; }
[Required]
public string billingcountry { get; set; }
public string phone { get; set; }
[Required]
public string email { get; set; }
[Required]
public string shippingaddress1 { get; set; }
public string shippingaddress2 { get; set; }
[Required]
public string shippingcity { get; set; }
public string shippingstate { get; set; }
[Required]
public string shippingzip { get; set; }
[Required]
public string shippingcountry { get; set; }
public bool goodstanding { get; set; }
public string userid { get; set; }
public Nullable<DateTime> insuranceexp { get; set; }
public virtual ICollection<invoice> invoices { get; set; }
public virtual ICollection<order> orders { get; set; }
}
this is my model...
And I have a data access layer...
public DbSet<tvc.viewModels.orders> orders { get; set; }
public DbSet<tvc.viewModels.customers> customers { get; set; }
The error is pretty straight-forward. There's no dbo.customers1 table in your database. As to why, there's really not enough information here to say, but the most likely causes are:
You're using Database First or Code First with an existing database, and your entities are out of sync with the database.
You're using Code First, don't have migrations enabled, and you've made a change to either your entities or your database. Again, out of sync.
You've specified an explicit table name, either via the Table attribute or fluent config, that doesn't exist. Either way, change either the explicit table name to what it should be or rename your database table so it matches.
There was an oversight in my ViewModel. I was pointing customer, which is the name of the database table and the model class, rather than the viewmodel class which is customers (with an s).

Entity Framework: Unable to determine the principal end of the relationship. Multiple added entities may have the same primary key

I'm getting this error while updating the model I'm sharing my code, please tell me the best solution for this.
Ticket Detail Class:
public class TicketDetail
{
[Key]
public int TicketDetailId { get; set; }
public int GenericOrderId { get; set; }
public int PartId { get; set; }
public int Quantity { get; set; }
public decimal? CustomerPrice { get; set; }
public string Status { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
public virtual Part Part { get; set; }
public virtual Ticket Ticket { get; set; }
}
OrderDetailClass:
public class OrderDetail
{
[Key]
public int OrderDetailId { get; set; }
public int GenericOrderId { get; set; }
public int PartId { get; set; }
public int Quantity { get; set; }
public decimal? UnitPrice { get; set; }
public string Status { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
public virtual Part Part { get; set; }
public virtual Order Order { get; set; }
}
Order Class:
public class Order : GenericOrder
{
public virtual ICollection<OrderDetail> OrderDetails { get; set; }
}
Ticket Class
public class Ticket : GenericOrder
{
public virtual ICollection<TicketDetail> TicketDetails { get; set; }
}
GenericOrderClass:
public abstract class GenericOrder
{
[Key]
public int GenericOrderId { get; set; }
public string ProcessId { get; set; }
public DateTime Date { get; set; }
public string FullName { get; set; }
public string Email { get; set; }
public string Company { get; set; }
public string Phone { get; set; }
public string Message { get; set; }
public decimal Total { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
}
and this is the controller class code
TryUpdateModel(order);
TryUpdateModel(ticket);
try
{
order.Date = DateTime.Now;
ticket.Date = DateTime.Now;
order.ProcessId = DateTime.Now.Ticks.ToString().Substring(12, 6);
ticket.ProcessId = order.ProcessId;
//Add the Order
storeDB.Orders.Add(order);
storeDB.Tickets.Add(ticket);
//Process the order
cart.CreateOrder(order);
cart.CreateTicket(ticket);
// Save all changes
storeDB.SaveChanges();
//return RedirectToAction("Complete",
// new { id = order.QuoteOrderId });
TempData["OrderSuccess"] = "Your order has been submitted successfully with the Process ID " + order.ProcessId;
TempData["OrderId"] = order.GenericOrderId;
TempData["Email"] = order.Email;
return RedirectToAction("Confirm");
}
catch (Exception e)
{
//Invalid - redisplay with errors
ModelState.AddModelError("", e.Message);
return View(order);
}
I have searched internet but couldn't find any solution.
Try saving Order and Ticket and after they are saved add Details to them.

How to generate a unique GUID when creating a new object in Entity Framework 5?

I've similar questions that refer to this annotation to solve their problem:
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
However, applying this to my relevant Entity Model does nothing.
When I call the .Add() method, it inserts the GUID as 00000000-0000-0000-0000-000000000000.
As you can see, the annotation I mentioned is present in the model:
using System;
using System.Collections.Generic;
public partial class Event
{
[System.ComponentModel.DataAnnotations.Schema.DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public System.Guid ID { get; set; }
public int AccountID { get; set; }
public string ExternalID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Location { get; set; }
public Nullable<System.DateTime> StartTime { get; set; }
public Nullable<System.DateTime> EndTime { get; set; }
public Nullable<bool> AllDay { get; set; }
public Nullable<System.Guid> ImageData { get; set; }
public string ImageUrl { get; set; }
public virtual Account Account { get; set; }
public virtual FetchedFile FetchedFile { get; set; }
}
How can I generate a unique GUID upon inserting a new Entity Object?
You can always initialize the Guid in a constructor.
public partial class Event
{
public Event()
{
ID = Guid.NewGuid();
}
public System.Guid ID { get; set; }
public int AccountID { get; set; }
public string ExternalID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Location { get; set; }
public Nullable<System.DateTime> StartTime { get; set; }
public Nullable<System.DateTime> EndTime { get; set; }
public Nullable<bool> AllDay { get; set; }
public Nullable<System.Guid> ImageData { get; set; }
public string ImageUrl { get; set; }
public virtual Account Account { get; set; }
public virtual FetchedFile FetchedFile { get; set; }
}

Resources