want efcore sql syntax, fluent api method for the example from a week - ef-fluent-api

Department {int Id,string Title,Staffs}
Staff {int Id, string Name, int DeptId}
var DeptStaff =
from dept in _context.Departments
select new
{
Department= dept,
StaffCount =
(from staff in _context.Staffs
where staff.DeptId == dept.Id
select staff).Count()
}
Staffs is a navigation property in Department class
gives error in inner query

Related

Case Milestones not created when testing apex class

Recently I stumbled upon problem getting code coverage for Apex code that evaluates case milestones by their target date values. When trying to create case in test class it does not create case milestone for it after insert although all the criteria is being met what is defined in entitlement process.
Also by reading articles - like this about entitlements it seems like I have created everything.
The Entitlement process is Active, Entitlement with associated Account that is linked to Case is created and linked to Case, Business Hours are valid, Entitlement process is linked to Entitlement. Case entry criteria matches what is defined in Entitlement Process for Milestones, but still in test class milestones are not created.
System.debug('case milestones = '+ cmss); statement returns empty list and logic that relies on case milestone target date cannot be covered. Is there something missing in test data?
Example of test class:
#IsTest
private class GetCaseTest {
#TestSetup
static void createTestData(){
Profile p = [SELECT Id FROM Profile WHERE Name='Customer Service Lightning'];
UserRole role = [SELECT ID, Name FROM UserRole WHERE Name Like 'NO%' LIMIT 1];
System.debug('#role: ' + role);
User u = new User(
Alias = 'standt',
Email='testmail#test.com',
EmailEncodingKey='UTF-8',
FirstName='Test',
LastName='Testing',
LanguageLocaleKey='en_US',
LocaleSidKey='en_US',
ProfileId = p.Id,
UserRoleId=role.Id,
TimeZoneSidKey='America/Los_Angeles',
UserName='testmail#test.com'
);
insert u;
Group g = new Group(
Name='NO CS',
Type = 'Queue'
);
insert g;
queuesobject q1 = new queuesobject(SObjectType = 'Case', queueid=g.id);
insert q1;
GroupMember member = new GroupMember();
member.UserOrGroupId = u.Id;
member.GroupId = g.Id;
insert member;
}
#isTest
static void getCaseFuture(){
User u = [SELECT Id, Email FROM User WHERE Email = 'testmail#test.com'].get(0);
System.runAs(u){
Id accRecType = Schema.SObjectType.Account.getRecordTypeInfosByName().get('B2B Account').getRecordTypeId();
Account acc = new account(name='Test Account', RecordTypeId= accRecType, OwnerId = u.Id);
insert acc;
Contact oContact = new contact(firstname='John',lastname='Doe',email='test#test.com',accountid=acc.id, OwnerId = u.Id);
insert oContact;
Entitlement entl = new entitlement(name='NO Entitlement',accountid=acc.id, StartDate=Date.valueof(System.now().addDays(-2)), EndDate=Date.valueof(System.now().addYears(2)));
insert entl;
List<SlaProcess> lstEntitlementProcess = [SELECT Id, Name FROM SlaProcess WHERE Name='NO Entitlement Process 1.3' and IsActive = true LIMIT 1];
System.debug('lstEntitlementProcess= '+lstEntitlementProcess);
entl.SlaProcessId = lstEntitlementProcess[0].id;
update entl;
BusinessHours bhours = [SELECT Id, Name FROM BusinessHours WHERE Name = 'NO Customer Service'].get(0);
Id recordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Card Administration').getRecordTypeId();
Group g = [SELECT Id FROM Group WHERE Type = 'Queue' AND Name = 'NO CS'].get(0);
Case c2 = new Case(
Subject = 'To be distributed from queue',
Status = 'In Progress',
Case_Re_opened__c = false,
OwnerId = g.Id,
CurrencyIsoCode = 'EUR',
Country__c = 'NO',
Case_Category__c = 'Card Block',
RecordTypeId = recordTypeId,
AccountId = acc.Id,
ContactId = oContact.Id,
EntitlementId = entl.Id,
slaStartDate=system.now(),
BusinessHoursId = bhours.Id
);
insert c2;
List<CaseMilestone> cmss = [SELECT Id, CaseId FROM CaseMilestone WHERE CaseId =: c2.Id];
System.debug('case milestones = '+ cmss);
System.debug('c2 = '+ c2);
System.debug('c2.OwnerId=> '+ c2.OwnerId);
}
Test.startTest();
GetCase.findCase();
// GetCase.findCase();
Test.stopTest();
}
}

Acumatica refer custom field to another custom field on different screen

I have created 2 custom fields(UsrFFA and UsrFreeFreightDay) as below in the Customers Screen.Customers Screen
Then I created similar fields on the Sales Order Screen as below
Sales Order
I want these fields on Sales Order screen to populate values for respective Customer ID.
I went through the training material T200 and found this code
protected void SOOrder_CustomerID_FieldUpdated(PXCache sender,PXFieldUpdatedEventArgs e)
{
SOOrder order = e.Row as SOOrder;
BAccount customer =
PXSelectorAttribute.Select<SOOrder.customerID>(sender, order)
as BAccount;
if (customer != null)
{
Contact defContact = PXSelect<Contact,
Where<Contact.bAccountID, Equal<Required<Contact.bAccountID>>,
And<Contact.contactID, Equal<Required<Contact.contactID>>>>>
.Select(Base, customer.BAccountID, customer.DefContactID);
if (defContact != null)
{
ContactExt contactExt = PXCache<Contact>
.GetExtension<ContactExt>(defContact);
sender.SetValue<SOOrderExt.usrCRVerified>(order,
contactExt.UsrCreditRecordVerified);
}
}
}
I am not able to understand this code and how should I use it in my customization.
You should subscribe to FieldUpdated handler for the SOOrder.CustomerID field and populate your custom fields on the Sales Order screen in the same way as shown in Example 5.2: Inserting a Default Detail Data Record of the T200 training class:
protected virtual void ShipmentLine_ProductID_FieldUpdated(PXCache sender, PXFieldUpdatedEventArgs e)
{
// Obtain the new data record that contains the updated
// values of all data fields
ShipmentLine line = (ShipmentLine)e.Row;
line.Description = string.Empty;
if (line.ProductID != null)
{
Product product = PXSelectorAttribute.Select<ShipmentLine.productID>(sender, line) as Product;
if (product != null)
{
// Copy the product name to the description of the shipment line
line.Description = product.ProductName;
}
}
}
You might also check Step 3.1: Adding the FieldUpdated Event Handler (CustomerMaint) and Step 5.2: Customizing Business Logic for the Sales Orders form (SOOrderEntry) from the T300 training class for additional samples.
The code snippet below should accomplish desired results on the Sales Orders screen. If you still have issues understanding the code below, I highly recommend you to go through the T300 training class for very detailed hands-on exercises with step-by-step instructions.
public class SOOrderEntryExt : PXGraphExtension<SOOrderEntry>
{
public void SOOrder_CustomerID_FieldUpdated(PXCache sender, PXFieldUpdatedEventArgs e)
{
var order = e.Row as SOOrder;
if (order.CustomerID != null)
{
var customer = PXSelectorAttribute.Select<SOOrder.customerID>(sender, order) as BAccountR;
if (customer != null)
{
var customerExt = customer.GetExtension<BAccountExt>();
var orderExt = order.GetExtension<SOOrderExt>();
orderExt.UsrFFA = customerExt.UsrFFA;
orderExt.UsrFreeFreightDay = customerExt.UsrFreeFreightDay;
}
}
}
}
Customize the attributes on the SOOrder field in the following way:
For UsrFFA field
[PXDBString(100)]
[PXUIField(DisplayName="FFA", Visible = true, Enabled = false)]
[PXFormula(typeof(Selector<SOOrder.customerID, BAccountExt.usrFFA>))]
For UsrFreeFreightDay field
[PXDBString(100)]
[PXUIField(DisplayName="Free Freight Day", Visible = true, Enabled = false)]
[PXFormula(typeof(Selector<SOOrder.customerID, BAccountExt.usrFreeFreightDay>))]

JPA Cascading removal of parent and Child

I'm trying to learn and understand JPA, and just have a couple of questions regarding deleting a parent and its children in one go. I'm using OpenJPA and EJB3. I have two entities, a Category and a Product. A Category contains many products and a product has a reference to its parent category. The category's list of products is set to cascade.
//Category
#Entity #NamedQueries({#NamedQuery(name = "Category.getCategoryByName", query = "SELECT c FROM Category c WHERE c.name = :name"),#NamedQuery(name = "Category.getCategoryByCategoryId", query = "SELECT c FROM Category c WHERE c.categoryid = :categoryid"), #NamedQuery(name = "Category.getAllCategories", query = "SELECT c FROM Category c left join fetch c.products")})
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=IDENTITY)
private Integer categoryid;
private String name;
//bi-directional many-to-one association to Product
#OneToMany(cascade={CascadeType.ALL}, orphanRemoval = true,
fetch = EAGER, mappedBy="category")
private List<Product> products;
}
//Product
#Entity
#NamedQueries({#NamedQuery(name = "Product.getProductsByCategory",
query = "SELECT p.code, p.description, p.name, p.productid, p.weight FROM Product p WHERE p.category.categoryid = :category_categoryid"),
#NamedQuery(name = "Product.getProductByName", query = "SELECT p FROM Product p WHERE p.name = :name"),
#NamedQuery(name = "Product.getProductByCode", query = "SELECT p FROM Product p WHERE p.code = :code"),
#NamedQuery(name = "Product.getProductByProductId", query = "SELECT p FROM Product p WHERE p.productid = :productid"),
#NamedQuery(name = "Product.getAllProducts", query = "SELECT p FROM Product p")})
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=IDENTITY)
private Integer productid;
private String code;
private String description;
private String name;
private Double weight;
//bi-directional many-to-one association to Category
#ManyToOne(optional = false)
#JoinColumn(name="CATEGORYID")
private Category category;
}
}
// The EJB
#Stateless
#LocalBean
public class ShopManagerBean implements Serializable {
#PersistenceContext(unitName = "TestEJBProject2", type = PersistenceContextType.TRANSACTION)
private EntityManager entityManager;
#TransactionAttribute(TransactionAttributeType.REQUIRED)
public void deleteCategory(Category category)
throws TestApplicationException {
try {
Category actualCat = entityManager.find(Category.class,
category.getCategoryid());
List<Product> products = actualCat.getProducts();
if (products != null) {
Iterator<Product> it = products.iterator();
while (it.hasNext()) {
Product p = it.next();
it.remove();
entityManager.remove(p);
}
}
entityManager.refresh(actualCat);
entityManager.remove(actualCat);
} catch (Exception e) {
e.printStackTrace();
throw new TestApplicationException("Error creating new Product", e);
}
}
}
If I use the following code in the deleteCategory method the EJB then I cannot delete the parent and children as I get an Optimistic Locking exception (An optimistic lock violation was detected when flushing object instance "entity.Product-101" to the data store. This indicates that the object was concurrently modified in another transaction.) - complaining about flushing the product child to the data store
Category actualCat = entityManager.find(Category.class, category.getCategoryid());
if (products != null) {
actualCat.getProducts().clear();
}
entityManager.remove(actualCat);
However, if I use the following code in the deleteCategory method then I can delete the parent and children...but only if I call entityManager.refresh(actualCat) after removing the children and before removing the parent (otherwise I get an optimistic locking exception). Could somebody please explain to me why this is the case and also what the correct/best way of doing a cascading delete with OpenJPA V2 would be?
Category actualCat = entityManager.find(Category.class, category.getCategoryid());
List<Product> products = actualCat.getProducts();
if (products != null) {
Iterator<Product> it = products.iterator();
while (it.hasNext()) {
Product p = it.next();
it.remove();
entityManager.remove(p);
}
}
entityManager.refresh(actualCat);
entityManager.remove(actualCat);
Thanks in advance for your help
Fais
Addition
Here is the db creation script:
--
CREATE SCHEMA "DB2ADMIN";
CREATE TABLE "DB2ADMIN"."CATEGORY" (
"CATEGORYID" INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY ( START WITH 1 INCREMENT BY 1 MINVALUE 1 MAXVALUE 2147483647 NO CYCLE CACHE 20),
"NAME" VARCHAR(50) NOT NULL
)
DATA CAPTURE NONE;
CREATE TABLE "DB2ADMIN"."PRODUCT" (
"PRODUCTID" INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY ( START WITH 1 INCREMENT BY 1 MINVALUE 1 MAXVALUE 2147483647 NO CYCLE CACHE 20),
"CODE" CHAR(15) NOT NULL,
"NAME" VARCHAR(50) NOT NULL,
"DESCRIPTION" VARCHAR(200) NOT NULL,
"WEIGHT" FLOAT(53) NOT NULL,
"CATEGORYID" INTEGER NOT NULL
)
DATA CAPTURE NONE;
ALTER TABLE "DB2ADMIN"."CATEGORY" ADD CONSTRAINT "CATEGORY_PK" PRIMARY KEY
("CATEGORYID");
ALTER TABLE "DB2ADMIN"."PRODUCT" ADD CONSTRAINT "PRODUCT_PK" PRIMARY KEY
("PRODUCTID");
ALTER TABLE "DB2ADMIN"."PRODUCT" ADD CONSTRAINT "PRODUCT_CATEGORY_FK" FOREIGN KEY
("CATEGORYID")
REFERENCES "DB2ADMIN"."CATEGORY"
("CATEGORYID")
ON DELETE CASCADE;

ComponentOne.TrueDBGrid binding

1 I am using ComponentOne.TrueDBGrid;
2 I am using UserList as the datasource;
3 I need filterbar and sortings for this grid ;
some important code like below:
public class User{
public int UserID{get;set;}
public string UserName{get;set;}
public Company TheCompany{get;set;}
}
public class Company{
public override ToString(){
return CompanyName;
}
public string CompanyName{get;set;}
}
List UserList
Question:
1 How can I bind UserList to the TrueDBGrid to show these Columns ?
|UserID|UserName|CompanyName|
I think these datafields should be UserID , UserName, TheCompany.CompanyName,But I can't see the CompanyName is empty;
2 I need change Company in this grid , so I need I add valueItems for CompanyName
I think these datafields should be UserID , UserName, TheCompany,and override Company.ToString() = CompanyName
But I can't sorting the companyName column and can't change company because the datatype is string can't covert to Company;
Is these a good way to resolve these problems ?
A bit late, but...
Add a readonly string property to UserList that returns TheCompany.CompanyName.

JPA: persist does not insert into join table

All,
I am using JPA for this application and annotations for Mapping entities. I have an entity called UserStory and another one called Revision. There is a OneToMany for UserStory to Revision.
#Entity
#Table(name = "user_story")
#NamedNativeQueries({
#NamedNativeQuery(name = "storyBacklog", query = "SELECT userstory.rank AS rank, userstory.description AS description, userstory.estimate AS estimate, userstory.name AS name, "
+ "userstory.id AS id, userstory.status AS status FROM user_story userstory ORDER BY userstory.rank ASC", resultClass = UserStory.class),
#NamedNativeQuery(name = "getCos", query = "SELECT conditions.cos As cos FROM story_cos conditions WHERE conditions.story_id=?1", resultSetMapping = "cosMapping") })
#SqlResultSetMappings({ #SqlResultSetMapping(name = "cosMapping", columns = #ColumnResult(name = "cos")) })
public class UserStory implements Serializable {
private static final long serialVersionUID = 248298400283358441L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
...
#OneToMany(cascade = CascadeType.ALL)
#JoinTable(name = "story_revisions", joinColumns = #JoinColumn(name = "story_id"), inverseJoinColumns = #JoinColumn(name = "revision_id"))
private Set<Revision> revisions;
here's Revision entity:
#Entity
#Table(name = "revision")
public class Revision implements Serializable {
private static final long serialVersionUID = -1823230375873326645L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(nullable = false)
private String description;
#Column(name = "date_created", nullable = false)
#Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
When I create a userStory; I add a revision on to it,
but the join table is not populated unless, I persist story first,
then add revision and merge it.
here's the code for saving a UserStory:
public UserStory saveUserStory(UserStory userStory) {
Revision revision = new Revision();
revision.setCreationDate(new Timestamp(System.currentTimeMillis()));
revision.setDescription("User story created");
Set<Revision> revisions = new HashSet<Revision>();
revisions.add(revision);
userStory.setRevisions(revisions);
return storyDao.create(userStory);
}
in StoryDao I call the persist method:
#Transactional(readOnly = false)
public UserStory create(UserStory userStory) {
if (userStory.getRank() == null) {
Integer highestRank = 0;
highestRank = (Integer) entityManager.createNativeQuery("select max(rank) from user_story")
.getSingleResult();
if (highestRank != null)
highestRank += 1;
else
highestRank = new Integer(1);
userStory.setRank(highestRank);
}
entityManager.persist(userStory);
LOGGER.debug("Added User Story with id " + userStory.getId());
entityManager.detach(userStory);
return userStory;
}
here's the SQL from LOGS
Hibernate:
insert
into
user_story
(description, estimate, name, rank, status)
values
(?, ?, ?, ?, ?)
Hibernate:
insert
into
revision
(date_created, description)
values
(?, ?)
Hibernate:
select
revision0_.id as id5_0_,
revision0_.date_created as date2_5_0_,
revision0_.description as descript3_5_0_
from
revision revision0_
where
revision0_.id=?
Hibernate:
select
userstory0_.id as id3_1_,
userstory0_.description as descript2_3_1_,
userstory0_.estimate as estimate3_1_,
userstory0_.name as name3_1_,
userstory0_.rank as rank3_1_,
userstory0_.status as status3_1_,
revisions1_.story_id as story1_3_3_,
revision2_.id as revision2_3_,
revision2_.id as id5_0_,
revision2_.date_created as date2_5_0_,
revision2_.description as descript3_5_0_
from
user_story userstory0_
left outer join
story_revisions revisions1_
on userstory0_.id=revisions1_.story_id
left outer join
revision revision2_
on revisions1_.revision_id=revision2_.id
where
userstory0_.id=?
I can see from here it saves the user story and revision, but then tries to run a join to see if the relation exists before doing an insert into the join table. Which of course it will not find because I am creating this object.
How do it get the join table populated in this case?
Works now. Here's the updated code
revisions.add(revision);
userStory = storyDao.create(userStory);
userStory.setRevisions(revisions);
return storyDao.update(userStory);
I am still not sure why this is required; the two step method where I persist an object then update it.