assigning multiple image urls to an item stored in sql server database - razor-pages

I am building an online shopping site using asp.net core razor pages, currently I have only one variable in my sql database table accepting a string as the image name but the image is stored in the root directory in images folder. This is my model
public class GasContainer
{
public int GasContainerId { get; set; }
public string Name { get; set; }
public string Weight { get; set; }
public string Color { get; set; }
public string Image { get; set; }
public double Price { get; set; }
public double Discount { get; set;}
[NotMapped]
public double DiscountedPrice => Price - Discount;
//public decimal Price { get; set; }
public enum EColor
{
Red = 0,
Yellow = 1,
Green = 2,
Blue = 3,
Gray = 4
};
public string Type { get; set; }
public int? BrandId { get; set; }
public Brand Brand { get; set; }
}
I want each gas container to have multiple image paths associated with it. How do I go about it since sql server does not accept an array as a data type?

I finally figured out how...
Add another table related to the GasContainer(one to many relationships) eg GasContainerImages table with imageurl property, copy the uploaded files to a folder of your choice and update the imageurl(s) of GasContainerImages with strings pointing to the folder with images

Related

Domain Driven Design Model

I am building ParkingReservation in DDD, In short means that people can invite place and when the car get in the camera identify the model and update the status of the place.
I divided the model to three Bounded contexts:
The first is Reservation Context that include the following objects:
`public class Lot
{
public int ID { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
public List<Place> Places { get; set; }
}
public class Place
{
public int ID { get; set; }
public int FloorNumber { get; set; }
public int RowNumber { get; set; }
public int ParkingNumber { get; set; }
}
public class Car
{
public int ID { get; set; }
public string Model { get; set; }
}
public class Driver
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public int Age { get; set; }
public Gender Gender { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public bool AcceptAdsToMail { get; set; }
public byte[] PictureData { get; set; }
public DateTime RegistrationTime { get; set; }
public DriverStatuses DriverStatuses { get; set; }
}
public class Reservation
{
public int ID { get; set; }
public Driver Driver { get; set; }
public Car Car { get; set; }
public Place Place { get; set; }
public DateTime OrderTime { get; set; }
public DateTime ParkingStartTime { get; set; }
public DateTime ParkingEndTime { get; set; }
public ParkingStatuses ParkingStatus { get; set; }
}
public class ParkingHistory
{
public int ID { get; set; }
public Place Place { get; set; }
public Driver Driver { get; set; }
public Car Car { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
}`
The Parking Lot has list of places
the Driver reserve place through the application
the saved place saved in the Reservation object and when the parking time
elapsed, new parkinghistory added to parkinghistories list that belong to driver and car so you can watch history per car or driver.
for this context of Reservation:
(1) Is it correct to put Driver and Reservation for the Aggregate Roots? or maybe Lot too?
(2) Place is entity or value object?
Thank you
The main goal of your use case is scheduling. You need to think about a consistency boundary around that idea. To avoid time slots overlapping for a place in a lot you will need to create a new abstraction for the purpose.
"PlaceInLotReservations" sounds as a good option as an value object to serve as a factory for a Reservation aggregate. In order to represent reality of how scheduling works you should feed that aggregate in the context of a day, so "PlaceInLotReservationsRepository" should has a "findByDate" method that collects all Reservations for a place in a given datetime.
So the semantics would be something like:
val placeInLotReservations = PlaceInLotReservationsRepository.findBy(datetime)
val reservation = placeInLotReservations.reserveFor(car, driver, startingTime, endingTime)
ReservationsRepository.save(reservation)
If there are lot of reservations in a place and so race conditions you can even make the VO smaller by passing in day quarters instead of a day for the initial look up.
BTW, can and driver are VOs in the context of the Reservation aggregate (they are not aggregates).
You can also have the history by querying the Reservation repository, you donĀ“t need ParkingHistory.
Hope it helps.

EntityFramework : Invalid column name *_ID1

I am trying to implement DbContext for couple of tables called 'Employee' and 'Department'
Relationship between Employee and Department is many to one. i.e. department can have many employees.
Below are the EntityFramework classes I designed ( CodeFirst approach )
[Table("Employee")]
public class Employee
{
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Column("Name")]
public string Name { get; set; }
[Column("Department_ID")]
public int Department_ID { get; set; }
public virtual Department Department { get; set; }
}
[Table("Department")]
public class Department
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Column("Name")]
public string Name { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
}
While adding Employee record I am getting below exception
"Invalid column name 'Department_ID1'."
I am not sure why EF is referring to Department_ID1. Do I need to add configuration in OnModelCreating method of DbContext?
I am using EF version 6.1.1
I've also gotten this problem in my EF one-many deals where the one has a List of the many property and my mapping didn't specify that property. For example take:
public class Notification
{
public long ID { get; set; }
public IList<NotificationRecipient> Recipients { get; set; }
}
then
public class NotificationRecipient
{
public long ID { get; set; }
public long NotificationID { get; set; }
public Notification Notification { get; set; }
}
Then in my mapping, the way that caused the Exception (the incorrect way):
builder.HasOne(x => x.Notification).WithMany()
.HasForeignKey(x => x.NotificationID);
What fixed it (the correct way) was specifying the WithMany property:
builder.HasOne(x => x.Notification).WithMany(x => x.Recipients)
.HasForeignKey(x => x.NotificationID);
Hi After spending some time I could fix this problem by using ForeignKey attribute on public virtual Department Department { get; set; } property of Employee class.
Please see below code.
[Table("Employee")]
public class Employee
{
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Column("Name")]
public string Name { get; set; }
[Column("Department_ID")]
public int Department_ID { get; set; }
[ForeignKey("Department_ID")]
public virtual Department Department { get; set; }
}
This fixed my problem. Are there any other solution to fix this? Using fluent API?
For me, the issue was resolved by removing a (duplicate?) virtual property.
Using the OP's example:
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public int Department_ID { get; set; }
public virtual Department Department { get; set; }
}
public class Department
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
}
Turns into:
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public int Department_ID { get; set; }
}
public class Department
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
}
In my case I added a virtual property on top of the auto generated property
I fixed it by adding the NotMapped attribute to my property, or you could configure with fluent api
public partial class Control
{
[NotMapped]
public virtual ICollection<Control> Children { get => this.InverseParent; set => this.InverseParent = value; }
}
I had the same error, my issue was the FK was a long but I had it as an int in the model. EF generated a new column because it didn't match types on the FK so it assumed they weren't the same and went ahead with making another one but putting 1 at the end because there was already one with the proper name. Making sure the types matched resolved the issue for me.
This can be fixed simply by putting [NotMapped] annotation on your virtual properties.
public class Employee
{
[ForeignKey("Department")]
public int Department_ID
[NotMapped]
public virtual Department Department { get; set; }
}
And in you modelBuilder:
modelBuilder.Entity<Employee>(entity =>
{
entity.HasOne(e => e.Department);
});
Just flip this around if you want to call by Department.
We use the [NotMapped] annotation so that EF Core will disregard it when looking at your database.

Get the _updatedAt field in Azure Mobile Services

I am using Azure Mobile Services to store and retrieve highscores for my XNA game. Azure provides a native _updatedAt column, but somehow I am not able to retrieve it.
This is my current code:
public class ScoreItem
{
public string Id { get; set; }
[JsonProperty(PropertyName = "user_name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "score")]
public int Score { get; set; }
[JsonProperty(PropertyName = "_updatedAt")]
public DateTime UpdatedAt { get; set; }
}
Any idea how to fix this?
I was able to find the mistake, system columns start with a double underscore. So the correct code would be
public class ScoreItem
{
public string Id { get; set; }
[JsonProperty(PropertyName = "user_name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "score")]
public int Score { get; set; }
[JsonProperty(PropertyName = "__updatedAt")]
public DateTime UpdatedAt { get; set; }
}

MVC using multiple tables , 2 generated with code first and one with DB first

I am new to MVC and i think someone answered this question before , so i apologize for re-posting it.
I've been a form based programmers for years , and now i am working on an MVC project for the first time, last 3 weeks i read a lot of books, articles, tutorials and watched a lot of videos about MVC.
Here is my question:
- I have 3 tables: Tasks, Customer and Employee
Each task has 1 customer and one employee assigned to it. I generated the Tasks table from an existing table i have on a SQL DB , but i followed "Code-First" to create the employee and Customer tables. I am not sure if i did the right relationships between those table. What i want to do is to display all tasks + the userNAME + CustomerName instead of UserID and CustomerID.
Here are my models:
Tasks:
public partial class Tasks
{
public string TaskID { get; set; }
public string Name { get; set; }
public System.DateTime StartDate { get; set; }
public Nullable<System.DateTime> DueDate { get; set; }
public Nullable<int> Complete { get; set; }
public string Description { get; set; }
public Nullable<int> Priority { get; set; }
public string Status { get; set; }
public Nullable<System.DateTime> AssignementDate { get; set; }
public Nullable<System.DateTime> CreationDate { get; set; }
[ForeignKey ("Employee")]
public string EmployeeID { get; set; }
public virtual ApplicationUser _User { get; set; }
[ForeignKey("Customer")]
public string CustomerID { get; set; }
public virtual CustomerModel _Customer { get; set; }
}
Customer:
public class CustomerModel
{
[Key]
public String ID { get; set; }
public String Number { get; set; }
}
Employee
public class EmployeeModel
{
[Key]
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Also How to access the employee first name from my Tasks controller.
Last question: is it ok to mix between models (Some code-first and some DB-first) Or should i follow one pattern.
Thanks a lot
You can use both pattern, but I recommend you my approach that you use CodeFirst, create entites to store data and viewmodels to display data:
public class Task
{
public int TaskID { get; set; }
//your other properties here...
public int EmployeeId { get; set; }
public int UserId { get; set; }
public int CustomerId { get; set; }
}
And in client lawyer, create ViewModel for Task model:
public class TaskViewModel
{
public Task Task { get; set; }
public EmployeeModel Employee { get; set; }
public ApplicationUser User { get; set; }
public CustomerModel Customer { get; set; }
}
In your GetTask() (Or LoadTasks()) method fill this view model:
public TaskViewModel GetTask(int id)
{
TaskViewModel model = new TaskViewModel();
model.Task = _db.GetTaskById(id);
model.Employee = _db.GetEmployeeById(model.Task.EmployeeId);
model.User = _db.GetUserById(model.Task.UserId);
model.Customer = _db.GetCustomerById(model.Task.CustomerId);
return model;
}
And now, you can get all data you want related to a task:
TaskId, TaskName, Created user's name + surname, Employee's name surname, Custemer's name + surname etc..

Cascade saving children objects in Orchard CMS

Lets say I have an object called Company that is represented like so:
public class Company
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual Address Address { get; set; }
}
public class Address
{
public virtual int Id { get; set; }
public virtual string Line1 { get; set; }
public virtual string Line2 { get; set; }
public virtual string Line3 { get; set; }
public virtual string Town { get; set; }
public virtual string County { get; set; }
public virtual string Postcode { get; set; }
public virtual double Longitude { get; set; }
public virtual double Latitude { get; set; }
}
When I create a new company, I also want the new address to be created too. At the moment, I can only get this to work by creating the address record and then creating the company record separately:
[HttpPost]
public ActionResult Add(Company company)
{
_addressRepo.Create(company.Address);
_companyRepo.Create(company);
return RedirectToAction("Index");
}
(Where _addressRepo and _companyRepo are of type IRepository<Address> and IRepository<Company> respectively)
How can I get all child objects to cascade save? So that ideally, when I call _companyRepo.Create(company);, Orchard handles all the child records for me?
I tried creating a new attribute so that properties can be marked as Cascade Save Update, but If I put a breakpoint on the Apply method it never appears to get hit.
public class CascadeSaveUpdateAttribute : Attribute {
}
public class CascadeSaveUpdateConvention :
AttributeCollectionConvention<CascadeSaveUpdateAttribute>
{
protected override void Apply(CascadeSaveUpdateAttribute attribute, ICollectionInstance instance)
{
instance.Cascade.SaveUpdate();
}
}
What can I do to get this Cascade Save functionality working?

Resources