Breeze.js /NET+EF complex object behaviors rather strange - javascript

I’m developing a custom data access layer to be consumed in breeze.js
What I have:
The Model:
public class Product
{
[Key]
public int ProductId { get; set; }
public string Upc { get; set; }
public string Name { get; set; }
public decimal MsrpPrice { get; set; }
public int Quantity { get; set; }
public virtual ICollection<ProductFeature> Features { get; set; }
public virtual B2BCategory InB2BCategory { get; set; }
public virtual ICollection<ImageDescriptor> Images { get; set; }
public int CategoryId {get; set;}
}
public class ProductFeature
{
public int ProductId { get; set; }
public string Name { get; set; }
public string GroupName { get; set; }
public string Operation { get; set; }
public decimal Value { get; set; }
}
public class ImageDescriptor
{
public int ProductId { get; set; }
public string Uri { get; set; }
public DateTime Updated { get; set; }
public bool IsDefault { get; set; }
}
The Context Provider:
public class ProductContextProvider : ContextProvider
{
private readonly ProductRepository repo =new ProductRepository();
public IQueryable<B2BCategory> Categories
{
get { return repo.Categories.AsQueryable(); }
}
public IQueryable<Product> Products
{
get
{
return repo.Products.OrderBy(p => p.ProductId).AsQueryable();
}
}
protected override string BuildJsonMetadata()
{
var contextProvider = new EFContextProvider<ProductMetadataContext>();
return contextProvider.Metadata();
}
protected override void SaveChangesCore(SaveWorkState saveWorkState)
{…
}
// No DbConnections needed
public override IDbConnection GetDbConnection()
{
return null;
}
protected override void OpenDbConnection()
{
// do nothing
}
protected override void CloseDbConnection()
{
// do nothing
}
}
internal class ProductMetadataContext : DbContext
{
static ProductMetadataContext()
{
Database.SetInitializer<ProductMetadataContext>(null);
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new ProductFeatureConfiguration());
modelBuilder.Configurations.Add(new ImageDescriptorConfiguration());
}
public DbSet<Product> Products { get; set; }
public DbSet<B2BCategory> Categories { get; set; }
}
internal class ImageDescriptorConfiguration : EntityTypeConfiguration<ImageDescriptor>
{
public ImageDescriptorConfiguration()
{
// I tried to mess up with key orders
HasKey(i => new { i.Uri, i.ProductId});
}
}
internal class ProductFeatureConfiguration : EntityTypeConfiguration<ProductFeature>
{
public ProductFeatureConfiguration()
{
HasKey(f => new { f.ProductId, f.Name });
}
}
I’m stuffing the Features and Images properties of a Product directly:
product.Features = new Collection<ProductFeature>();
product.Images = new Collection<ImageDescriptor>();
…
var imgd = new ImageDescriptor
{
ProductId = product.ProductId,
Updated = DateTime.Now,
Uri = defsmall,
IsDefault = !product.Images.Any()
}
product.Images.Add(imgd);
…
var pf = new ProductFeature
{
ProductId = product.ProductId,
GroupName = "Size",
Name = size,
Value = size == "Small" ? new decimal(.75):size == "Medium" ? new decimal(1.3):new decimal(1.8),
Operation = "*"
};
product.Features.Add(pf);
Totally there are, say, 3 product features and 2 images per product item.
In the client side I query this like:
return entityQuery.from('Products').using(EntityManager).execute();
And… I’ve got the very strange thing:
The images property contains an empty array, the features property contains an array of 5!!! elements – 3 of type ProductFeature and 2 of type ImageDescriptor.
I think this is a bug – could you help me, please?

I don't see any code that creates a breeze EntityManager and adds or attaches your newly created entities and then saves them. Please take a look at the Breeze examples in the downloadable zip from the BreezeJs website.

Related

Passing a list from angular to c# through http request

My method in c# receives a list as a parameter, I am trying to call this method in angular by passing it an array, but the problem is that the info doesn't reach the c# method, the list is always empty, even though there was information in the angular array.
export class StationAllocationPostModel{
idAppDeviceOwnerEntity: number;
idAppDeviceOwnerEntityOriginal: number;
idAppDeviceOwnerEntityRentalLocationId: number;
Observations: string;
selectedAppDevices: StationAllocationModel[];
}
createNewStationAllocation(selectedAppDevices: StationAllocationPostModel){
return this.post("home/CreateAppDeviceRentalLocationAllocation", selectedAppDevices, {
params: {
'idAppDeviceOwnerEntity': selectedAppDevices.idAppDeviceOwnerEntity,
'idAppDeviceOwnerEntityRentalLocationId': selectedAppDevices.idAppDeviceOwnerEntityRentalLocationId,
'Observations': selectedAppDevices.Observations,
'selectedAppDevices': selectedAppDevices.selectedAppDevices
}
});
}
public post(url: string, data: any, options = null) {
return new Promise<any>((resolve, reject) => {
let response;
this.http.post(
this.baseUrl + url,
{
data: data
},
{
headers: options ? options.headers : null,
observe: options ? options.observe : null,
params: options ? options.params : null,
reportProgress: options ? options.reportProgress : null,
responseType: options ? options.responseType : null,
withCredentials: options ? options.withCredentials : null
}
)
.subscribe(
data => {
response = data;
if (response && !response.success) {
if (response.response.ServerResponse[0].MessageType == "NOSESSIONEXCEPTION") {
localStorage.removeItem('userSession');
this.router.navigate(['/login'], { queryParams: { returnUrl: this.router.url } });
}
}
},
error => {
resolve(null);
this.handleError(url, options ? options.params : null );
console.log(error);
}, () => {
if (response) {
resolve(response);
} else {
resolve(null);
}
}
);
})
}
This is my c# method:
public Object CreateAppDeviceRentalLocationAllocation(<other params>, List<AppDeviceRentalLocationAllocationHistoryExtended> selectedAppDevices)
{
...
}
I am expecting that the c# method receives a list with elements, but it always comes out empty for some reason. The 'other params' are getting the right information, so I don't know what's wrong with the list.
Sorry for the long post, I'm new here.
Could you please form a param object on the C# method that holds the following :
public class SelectedAppDevice
{
public int idAppDevice { get; set; }
public int idAppDeviceOwnerEntity { get; set; }
public int idAppDeviceOwnerEntityRentalLocationId { get; set; }
public string Observations { get; set; }
public string DeviceId { get; set; }
public string EntityRentalLocationName { get; set; }
public DateTime CreationDate { get; set; }
public DateTime EndDate { get; set; }
public string CreatedByUserName { get; set; }
public int RentalStatus { get; set; }
public int idAppDeviceRental { get; set; }
public bool IsRentalStart { get; set; }
public bool IsRentalEnd { get; set; }
public object idNextExpectedEntityRentalLocationName { get; set; }
public object NextExpectedEntityRentalLocationName { get; set; }
public string LastKnownEntityRentingId { get; set; }
public string CallerId { get; set; }
public int RentalStatusId { get; set; }
public int DeviceStatusId { get; set; }
}
public class Data
{
public string Observations { get; set; }
public int idAppDeviceOwnerEntityRentalLocationId { get; set; }
public int idAppDeviceOwnerEntity { get; set; }
public List<SelectedAppDevice> selectedAppDevices { get; set; }
}
public class RootObject
{
public Data data { get; set; }
}
and make it as a controller method parameter :
public Object CreateAppDeviceRentalLocationAllocation(RootObject param)
{
...
}

Have to show Model data into View using JavaScript MVC C#

I have page where I save user, contact and address details. The users could have multiple contact and address, So I have added the control to populate dynamically.
Form is working fine, except if any exception occurrs, the controller action return view with model.
This follows the structure of Model:
Model
public class UserModel
{
public UserDetail User { get; set; }
public IList<UserContact> Contact { get; set; }
public IList<UserAddress> Address { get; set; }
}
Contact Model :
public partial class UserContact
{
public int Id { get; set; }
public int UserId { get; set; }
public string ContactType { get; set; }
public string Mobile { get; set; }
public string Email { get; set; }
public bool IsActive { get; set; }
public virtual UserDetail UserDetail { get; set; }
}
Address Model
public partial class UserAddress
{
public int Id { get; set; }
public int UserId { get; set; }
public string AddressType { get; set; }
public string AddressName { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostCode { get; set; }
public bool IsActive { get; set; }
public virtual UserDetail UserDetail { get; set; }
}
When value return, the following function suppose to check the Contact and Address and then then populate each record in dynamic created input section in view.
<script type="text/javascript">
$(document).ready(function () {
AddDynamicData();
function AddDynamicData() {
var valuesContacts = eval('#Html.Raw(Json.Encode(Model.Contact))');
var valuesAddresses = eval('#Html.Raw(Json.Encode(Model.Address))');
if (valuesContacts != null) {
var iContact = 0;
$(valuesContacts).each(function () {
$("#divContact").append(GetDynamicContact(iContact++, valuesContacts.contactType, valuesContacts.mobile, valuesContacts.email));
});
}
if (valuesAddresses != null) {
var iAddress = 0;
$(valuesAddresses).each(function () {
$("#divAddress").append(GetDynamicAddress(iAddress++, valuesAddresses.addressType, valuesAddresses.addressName, valuesAddresses.addressLine1, valuesAddresses.addressLine2, valuesAddresses.city, valuesAddresses.state, valuesAddresses.postCode));
});
}
}
</script>
The Function does not work properly, It does create the field but does not populate the user input data into textbox... Please advise how to fix the same and how to populate the records in view....
Added the View after submitting the form
<Update>
#Updated New Code with function & added screenshot
</Update>

Service Return Empty Lists To Api Controller

I am working in service fabrics micro services , where i need to fetch record for an object. when I send request to API , it shows me empty lists while rest of the data is in place. while debugging I came to know that before returning to API controller my service object has all the data expected i.e lists has data , but when it comes back to web API the lists are empty.
After searching for solution over web I came to know that every time a request is to the API the lists are recreated , so it shows empty result. Any Solutions to come out of this problem?
Here is my piece of code.
The following Is the Web Api Method.
[HttpGet()]
[Route("edit/{readingListId}")]
[ProducesResponseType(typeof(List<GetReadingListDTO>), (int)HttpStatusCode.OK)]
[ProducesResponseType(typeof(List<GetReadingListDTO>), (int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> GetReadingListById(int readingListId)
{
try
{
var readingList = await this._readingListService.GetReadingListByIdAsync(readingListId);
return Ok(readingList);
}
catch (Exception ex)
{
this._logger.LogError(ex.Message);
return BadRequest();
}
}
The following Is the Service Method.
public async Task<Domain.ReadingList> GetReadingListByIdAsync(int readingListId)
{
try
{
Domain.ReadingList readingList = await _repository.FindById(readingListId);
return readingList;
}
catch (Exception ex)
{
throw;
}
}
Moreover , This Is My Entity.
public class ReadingList : EntityBase, IAggregateRoot, IAggregateCreateRoot, IAggergateUpdateRoot, IAggregateDeleteRoot
{
public ReadingList()
{
this.Items = new List<ReadingListItem>();
this.Assignees = new List<ReadingListAssignee>();
}
public int Id { get; set; }
public EntityType EntityTypeId { get; set; }
public int EntityId { get; set; }
public string Title { get; set; }
public DateTime CompletionDate { get; set; }
public int ReminderDay { get; set; }
public string ReminderDayType { get; set; }
public bool SendReminder { get; set; }
public int CreatedBy { get; set; }
public DateTime CreatedDate { get; set; }
public int? UpdatedBy { get; set; }
public DateTime? UpdatedDate { get; set; }
public int? DeletedBy { get; set; }
public DateTime? DeletedDate { get; set; }
public bool? Deleted { get; set; }
public List<ReadingListItem> Items { get; private set; }
public List<ReadingListAssignee> Assignees { get; private set; }
}
Thanks!
Edited
The Issue Was Resolved , By Simply Changing The dll Versions.One Of The Service Had And Old Version While The Version Was Updated In The Other One.
Thanks For The Help.

KendoUI treeview children are displayed as undefined

I have a treeview in kendoUI in which main nodes are calling into an mvc controller and that controller looks to whether there is an nullable id passed in and then uses a different model.
What I hit the url : http://localhost:2949/Report/GetReportGroupAssignments
I see this JSON
[
{"Id":1,"ReportGroupName":"Standard Reports","ReportGroupNameResID":null,"SortOrder":1},
{"Id":2,"ReportGroupName":"Custom Reports","ReportGroupNameResID":null,"SortOrder":2},
{"Id":3,"ReportGroupName":"Retail Reports","ReportGroupNameResID":null,"SortOrder":3},
{"Id":4,"ReportGroupName":"Admin Reports","ReportGroupNameResID":null,"SortOrder":5},
{"Id":5,"ReportGroupName":"QA Reports","ReportGroupNameResID":null,"SortOrder":4}
]
Now my mvc controller looks like this
public JsonResult GetReportGroupAssignments(int? id)
{
var model = new List<ReportGroup>();
var defModel = new List<ReportDefinition>();
try
{
if (id == null)
{
model = _reportService.GetReportGroups("en-us").ToList();
return Json(model, JsonRequestBehavior.AllowGet);
}
else
{
defModel = _reportService.GetReportDefinitions().Where(e=>e.ReportGroupID ==Convert.ToInt32(id)).ToList();
return Json(defModel, JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
Logger.Error(ex, "Error loading LoadReportList.");
return null;
}
}
My Kendo javascript looks like the following:
var serviceRoot = "/Report"; // "//demos.telerik.com/kendo-ui/service";
homogeneous = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: serviceRoot + "/GetReportGroupAssignments", //"/LoadReportTree", // "/Employees",
dataType: "json"
}
},
schema: {
model: {
id: "Id" //"ReportGroupName"
,hasChildren: "Id"
}
}
});
var treeview = $("#treeview").kendoTreeView({
expanded: true,
dragAndDrop: true,
dataSource: homogeneous,
dataTextField: "ReportGroupName"
}).data("kendoTreeView");
Seems that the calls (which I discovered that children records have a "load" method that it called behind the seens, so basically I pass in the ID in order to get the data from the other model ( table in db)
(Id is mapped with automapper to ReportGroupID )
So when i click to the left of "Standard Rports" I am getting all of these children as undefined, How do I get these to show up properly?
Update: My ReportDefinition class:
public class ReportDefinition {
public override int Id { get; set; }
public string ReportKey { get; set; }
public string ReportName { get; set; }
public int? ReportNameResID { get; set; }
public string ReportDef { get; set; }
public int? ReportDefinitionResID { get; set; }
public string ReportAssembly { get; set; }
public string ReportClass { get; set; }
public int ReportGroupID { get; set; }
public int AppID { get; set; }
public int SortOrder { get; set; }
public bool IsSubReport { get; set; }
}
I think your problem is that the class ReportDefinition does not have a property called: ReportGroupName. That is why TreeView displays 'undefined'.
Try adding this Property to your ReportDefinition class like:
public class ReportDefinition {
// Other Properties
// I guess this property is missing
public string ReportGroupName { get; set; }
}

breezejs: navigation property not added to entity

I've configured my WebAPI ODATA service (using 5.0.0-rc1 for $expand and $select support) and everything seems to work fine but navigation properties.
The metadata does contain my navigation property (OpenPositions on Mandate) :
Then my breeze query is the following:
function search() {
var query = breeze.EntityQuery.from("Mandates").expand("OpenPositions").inlineCount();
return manager.executeQuery(query.using(service)).then(function (result) {
logger.info(result);
}).fail(function (error) {
logger.error(error);
});
}
The WebAPI controller :
[Queryable(AllowedQueryOptions= AllowedQueryOptions.All)]
public override IQueryable<Mandate> Get()
{
return new List<Mandate>() { new Mandate() {
Id = 1,
PolicyNumber = "350000000",
OpenPositions = new List<OpenPosition>(){
new OpenPosition(){ Id = 1, Amount = 2300, Mandate_Id = 1 },
new OpenPosition(){ Id = 2, Amount = 2100, Mandate_Id = 1 }
}},
new Mandate() {
Id = 2,
PolicyNumber = "240000000" ,
OpenPositions = new List<OpenPosition>(){
new OpenPosition(){ Id = 3, Amount = 2500, Mandate_Id = 2 },
new OpenPosition(){ Id = 2, Amount = 2100, Mandate_Id = 2}
}
} }.AsQueryable<Mandate>();
}
Nothing spectacular. But although my Mandate entities are coming back in the resultset, they do not have their OpenPositions collection.
As a test, if I add .select("OpenPositions") to my breeze query, then I get an error:
unable to locate property: OpenPositions on entityType: Mandate:#WebAPINoBreeze.Models
Why could that be ?
[EDIT]
query.entityType.NavigationProperties is an empty array, so that's probably a clue... It seems breeze could not build navigationproperties out of the metadata.
[EDIT]
foreign key added. problem still there:
public class Mandate
{
public int Id { get; set; }
public string PolicyNumber { get; set; }
public EStatus Status { get; set; }
public virtual List<OpenPosition> OpenPositions { get; set; }
}
public class OpenPosition
{
public int Id { get; set; }
public decimal Amount { get; set; }
[ForeignKey("Mandate")]
public int Mandate_Id { get; set; }
}
**[EDIT] **
For some reasons the [ForeignKey("Mandate")] attribute was removed at compile time (I think it's because the model class is generated. I've found a workaround and the metadata now contains the foreign key MandateId to Mandate in the OpenPositions :
You must define a foreign key as Breeze associations require FKs. http://www.breezejs.com/documentation/navigation-properties
[EDIT]
Your bi-directional association should look like this:
public class Mandate
{
public int Id { get; set; }
public string PolicyNumber { get; set; }
public virtual ICollection<OpenPosition> OpenPositions { get; set; }
}
public class OpenPosition {
public int Id { get; set; }
public decimal Amount { get; set; }
public int MandateId { get; set; }
public Mandate Mandate {get; set; }
}

Categories

Resources