Breeze saving strategy - angularjs

I'm creating my first spa with angular and breeze. So for so good and i'm very happy with the progress I've made. But now I'm stuck on my editing and saving my entity product (example class below). When I edit a product i also call the related products, and I have a checkbox (on saving) that says "override related products with same info". But what is the best way to do this? Server side? Should i expand the model on the client side? Are there examples available?
Product:
public class Product
{
#region Fields
private ICollection<ProductCategory> _productCategories;
private ICollection<ProductManufacturer> _productManufacturers;
private ICollection<ProductPicture> _productPictures;
private ICollection<ProductSpecificationAttribute> _productSpecificationAttributes;
private ICollection<ProductTierPrice> _productTierPrices;
#endregion Fields
#region Properties
public int Id { get; set; }
public ProductType ProductType { get; set; }
public int ParentGroupedProductId { get; set; }
public bool VisibleIndividually { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string MetaTitle { get; set; }
public string MetaDescription { get; set; }
public int DisplayOrder { get; set; }
public bool LimitedToStores { get; set; }
public string Sku { get; set; }
public string UniqueCode { get; set; }
public decimal Price { get; set; }
public decimal OldPrice { get; set; }
public decimal? SpecialPrice { get; set; }
public DateTime? SpecialPriceStartDateTimeUtc { get; set; }
public DateTime? SpecialPriceEndDateTimeUtc { get; set; }
public decimal DiscountPercentage { get; set; }
public bool HasTierPrices { get; set; }
public TaxRate TaxRate { get; set; }
public bool SyncToShop { get; set; }
public bool Deleted { get; set; }
public bool Locked { get; set; }
public State State { get; set; }
public DateTime? DateChanged { get; set; }
public DateTime? DateCreated { get; set; }
#endregion Properties
#region Mapping
public virtual ICollection<ProductCategory> ProductCategories
{
get { return _productCategories ?? (_productCategories = new List<ProductCategory>()); }
protected set { _productCategories = value; }
}
public virtual ICollection<ProductManufacturer> ProductManufacturers
{
get { return _productManufacturers ?? (_productManufacturers = new List<ProductManufacturer>()); }
protected set { _productManufacturers = value; }
}
public virtual ICollection<ProductPicture> ProductPictures
{
get { return _productPictures ?? (_productPictures = new List<ProductPicture>()); }
protected set { _productPictures = value; }
}
public virtual ICollection<ProductSpecificationAttribute> ProductSpecificationAttributes
{
get { return _productSpecificationAttributes ?? (_productSpecificationAttributes = new List<ProductSpecificationAttribute>()); }
protected set { _productSpecificationAttributes = value; }
}
public virtual ICollection<ProductTierPrice> ProductTierPrices
{
get { return _productTierPrices ?? (_productTierPrices = new List<ProductTierPrice>()); }
protected set { _productTierPrices = value; }
}
#endregion Mapping
}
Related Product:
public class RelatedProduct
{
#region Fields
#endregion Fields
#region Properties
public int Id { get; set; }
public int ProductId1 { get; set; }
public int ProductId2 { get; set; }
public int DisplayOrder { get; set; }
public State State { get; set; }
#endregion Properties
//#region Mapping
//public virtual Product Product1 { get; set; }
//public virtual Product Product2 { get; set; }
//#endregion Mapping
}

Capture Changes of All Products in Clinent Jquery Array and send to Server Side..
Serverside change your controller method argument to IEnumerable products , so you can save all changes in Batch
If you want to update only change value use HttpPatch on server side and update changed value only

Related

Entities with problems and limitations

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

Angularjs WebApi is not working in Asp.net MVC Entity Framework

This error is Occur after running the web application. this is picture of inspect elements of google chrome.
See Image
See Second Image
i want to us entity framework
here is class code... when i comment the
public virtual List tblproduct { get; set; } and
public virtual List tblproduct { get; set; } this its working perfetcly how to completety use entity framework mvc in it
[Table("tblCatagory")]
public class AddCatagory
{
public int Id { get; set; }
[StringLength(56)]
public string CataName { get; set; }
public virtual List<Product> tblproduct { get; set; }
//public virtual List<AddSubCatagory> tblsubcatagory { get; set; }
}
[Table("tblSubCatagory")]
public class AddSubCatagory
{
public int Id { get; set; }
[StringLength(56)]
public string SubCataName { get; set; }
public int AddCatagoryId { get; set; }
public virtual AddCatagory tblcatagory { get; set; }
public virtual List<Product> tblproduct { get; set; }
}
product class code
[Table("tblProduct")]
public class Product
{
public int Id { get; set; }
[StringLength(56)]
public string ProductName { get; set; }
[StringLength(156)]
public string ProductDes { get; set; }
public int ProductQty { get; set; }
public double ProductRate { get; set; }
public double Inches { get; set; }
public DateTime Date { get; set; }
public int AddCatagoryId { get; set; }
public int AddSubCatagoryId { get; set; }
public virtual AddCatagory tblcatagory{ get; set; }
public virtual AddSubCatagory tblsubcatagory{ get; set; }
}
wepapi controller
public List<Product> Getproducts()
{
var result = db.products.ToList();
return result;
}
angularjs code..
GetAllPro();
function GetAllPro() {
$http.get("/api/Products").then(function (response) {
$scope.Pro = response.data;
}, function () {
alert("Error")
})
}

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.

Any obvious reason why my breeze entity child nodes won't expand?

I can't figure out why my child nodes are either null or have a count of 0, even though there's associated data in the db.
Parent Class "Project"
public partial class Project
{
public Project()
public int Id { get; set; }
public string Name { get; set; }
public int ProjectOwnerId { get; set; }
public int CurrentMilestoneId { get; set; }
public int StatusId { get; set; }
public virtual Milestone CurrentMilestone { get; set; }
public virtual ProjectStatus Status { get; set; }
public virtual ICollection<ProjectContact> Contacts { get; set; }
public virtual ProjectAddress Address { get; set; }
}
Child node property "CurrentMilestone" comes back null
public partial class Milestone
{
public int Id { get; set; }
public int MasterMilestoneId { get; set; }
public string Name { get; set; }
public virtual MasterMilestone MasterMilestone { get; set; }
public virtual ICollection<Project> Projects { get; set; }
}
Child node property "Contacts" comes back with an array of 0, even though there's valid matching data.
public partial class ProjectContact
{
public int Id { get; set; }
public int ProjectId { get; set; }
public int PersonId { get; set; }
public string Title { get; set; }
public virtual Person Person { get; set; }
public virtual Project Project { get; set; }
}
Using the HotTowel angular/breeze I'm running this..
return EntityQuery.from("Projects")
.orderBy(orderBy)
.expand("currentMilestone.masterMilestone, projectOwnerCompany, contacts, address")
.using(self.manager).execute()
.then(querySucceeded, self._queryFailed);
function querySucceeded(data) {
projects = data.results;
return projects;
}
Controller:
[HttpGet]
public IQueryable<Project> Projects()
{
return _contextProvider.QueryAllReadOnly<Project>();
}
What's weird is some of them work, like Status works but leaseStatus doesn't (not shown, setup the same way) without expanding it.
Just to add more info, if I run this against the API, ..../Projects?$expand=Status%2CCurrentMilestone%2CLeaseStatus%2CCurrentMilestone%2FMasterMilestone%2CContacts%2CContacts%2FPerson&
In Fiddler the child nodes aren't expanded.
Figured it out..
Change the Controller from ReadOnly to non-readonly.
From
[HttpGet]
public IQueryable<Project> Projects()
{
return _contextProvider.QueryAllReadOnly<Project>();
}
To
[HttpGet]
public IQueryable<Project> Projects()
{
return _contextProvider.QueryAll<Project>();
}

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.

Resources