copy entity in entity framework? - wpf

For example I have a wpf window bound to an customer Entity (let suppose it's cus1). Then I load another entity from context :
customer cus2 = context.customers.where(x=>x.id=10).FirstOrDefault();
Now I want cus1 = cus2 ? I can do this way :
cus1.name = cus2.name;
cus1.address = cus2.address;
...
...
This way meets my case (the content of textboxs in the form change immediately into values of cus2) but I wonder if there is anyway to make it shorter since cus1=cus2 doesn't work ?
Thanks

You can use the memberwise Clone method to make a shallowcopy of a business object:
See http://msdn.microsoft.com/de-de/library/system.object.memberwiseclone.aspx

You could also use Serialization or Reflection, to do it on your own. However both oof the methods are slower then writing it directly.
Take a look at this article. Maybe you will find it helpful:
http://www.codeproject.com/KB/dotnet/CloningLINQ2Entities.aspx
Edit:
Btw. Remember, using using MemberwiseClone, in case of ReferenceTypes will effect in copying the references, not objects.

If you want to update the values of a Customer entity in memory with the newest values in the datastore you can use the Refresh method on your ObjectContext.
Here is the documentation.
In your case it would look like:
context.Refresh(RefreshMode.StoreWins, cus1);
If you really want to map two entities you could have a look at AutoMapper. AutoMapper will help you by automatically mapping entities to each other with a default setup that you can tweak to your needs.

Related

SuiteCommerce Advanced - Show a custom record on the PDP

I am looking to create a feature whereby a User can download any available documents related to the item from a tab on the PDP.
So far I have created a custom record called Documentation (customrecord_documentation) containing the following fields:
Related item : custrecord_documentation_related_item
Type : custrecord_documentation_type
Document : custrecord_documentation_document
Description : custrecord_documentation_description
Related Item ID : custrecord_documentation_related_item_id
The functionality works fine on the backend of NetSuite where I can assign documents to an Inventory item. The stumbling block is trying to fetch the data to the front end of the SCA webstore.
Any help on the above would be much appreciated.
I've come at this a number of ways.
One way is to create a Suitelet that returns JSON of the document names and urls. The urls can be the real Netsuite urls or they can be the urls of your suitelet where you set up the suitelet to return the doc when accessed with action=doc&id=_docid_ query params.
Add a target <div id="relatedDocs"></div> to the item_details.tpl
In your ItemDetailsView's init_Plugins add
$.getJSON('app/site/hosting/scriptlet.nl...?action=availabledoc').
then(function(data){
var asHtml = format(data); //however you like
$("#relatedDocs").html(asHtml);
});
You can also go the whole module route. If you created a third party module DocsView then you would add DocsView as a child view to ItemDetailsView.
That's a little more involved so try the option above first to see if it fits your needs. The nice thing is you can just about ignore Backbone with this approach. You can make this a little more portable by using a service.ss instead of the suitelet. You can create your own ssp app for the function so you don't have to deal with SCAs url structure.
It's been a while, but you should be able to access the JSON data from within the related Backbone View class. From there, within the return context, output the value you're wanting to the PDP. Hopefully you're extending the original class and not overwriting / altering the core code :P.
The model associated with the PDP should hold all the JSON data you're looking for. Model.get('...') sort of syntax.
I'd recommend against Suitelets for this, as that's extra execution time, and is a bit slower.
I'm sure you know, but you need to set the documents to be available as public as well.
Hope this helps, thanks.

How to save child properties?

Breeze & Angular & MV*
I get an invoice object and expand it's necessary properties: Customer, Details, etc.
To access detail properties is easy, invoice.detail[n].property. And saving changes to existing properties (1 - n) is also easy. In my UI, I simply loop through my object vm.invoice.details to get & display all existing details, bind them to inputs, edit at will, call saveChanges(), done!
(keep in mind, in this UI, I need to complete the following too....)
Now, I have blank inputs for a new detail I need to insert.
However, I need to insert a new detail into the existing array of invoice details.
For example: invoice #5 has 3 details (detail[0], detail[1], detail[2]). I need to insert into this existing invoice, detail[3], and call saveChanges()
I've tried to call the manger.createEntity('invoice') but it complains about FK constraints. I know you can pass values as a second argument in createEntity('obj', newvalues)...but is that the correct and only method?
Seems like this should all be much easier but, well, I am at a loss so, please help where you can. TIA!
Take a look at the DocCode sample which has tests for all kinds of scenarios including this one.
Perhaps the following provides the insight you're looking for:
function addNewDetail() {
var newDetail = manager.createEntity('Detail', {
invoice: vm.currentInvoice,
... other initial values
});
// the newDetail will show up automatically if the view is bound to vm.details
}
Notice that I'm initializing the parent invoice navigation property. Alternatively, I could just set the Detail entity's FK property inside the initializer:
...
invoiceId: vm.currentInvoice.id,
...
Either way, Breeze will add the new detail to the details collection of the currentInvoice.
Your question spoke in terms of inserting the new Detail. There is no need to insert the new Detail manually and you can't manage the sort order of the vm.currentInvoice.details property any way.
Breeze has no notion of sort order for collection navigation properties.
If you need to display the details in a particular order you could add a sorting filter to your angular binding to vm.currentInvoice.details.
Make sure you have correct EntityName, because sometimes creating entity is a not as simple as it seems.Before working with entities see
http://www.getbreezenow.com/documentation/creating-entities
I will suggest you to look ur metadata file, go to last line of your file, you can see the field named "entitySet"
"entitySet":{"name":"Entity_Name","entityType":"Self.Entity_Name"}
check the entityName here i took as "Entity_Name" and then try to create the entity and use this name
manger.createEntity('Entity_Name');

Proper way to access entity key outside the original class

I'm coding my first GAE web app in Python. I need to collect ~30 properties and instantiate a Client object (I'm using Model.db). I'd like to accomplish this on 4 separate sequential forms. If I use a separate page handler for each form, what is the best way to extract and reference the key or id on each form and put data into the same data entity? How do I avoid a global variable?
Not sure I follow... You may need to explain the issue a little more clearly.
First, do not use a global variable.
You can have 4 forms on the same template, all with the same handler. Give each a separate hidden attribute. Or, depending on your templating package, you should be able to access the form by ID.
In your handler:
entity = MyModel.get_by_key_name('my_key_name')
if request.method == 'POST':
if request.POST['hidden_field'] == 'firstform':
entity['prop_1'] = form.prop_1.data
...
if request.POST['hidden_field'] == 'secondform':
...
...
entity.put()
else:
return <template>
You will need to modify the syntax above to suit your templating pkg.

ModX Revo Database: Relation between member groups and document groups

I'm creating some custom queries and need to figure out the relation between Member Groups and Document Groups.
My ultimate goal is to display the resources belonging to a particular User Group when a user log in. I am able to get their User ID from Sessions and so the relations I have figured out so far are:
User ID -> Member Groups Table -> ??Unknown table that pairs Member Groups with Document Groups?? -> Document Groups Table- > Resources Table
I just cant find that missing table(s)!
If any one can help me out that would be awesome!
Thanks
(ps: using Revo)
EDIT: added image for assitance
You could use some of the built-in MODX methods to achieve this.
This is not tested and might not work, but this might be a way to do it:
// userGroups = membergroups
$userGroups = $user->getUserGroups();
foreach ($userGroups as $userGroup) {
$resGroups = $userGroup->getResourceGroups();
foreach ($resGroups as $resGroup) {
$resources = $resGroup->getResources();
// merge resources into an array or something
}
}
Check out moduser.class.php, modusergroup.class.php, and modresourcegroup.class.php to see the queries behind these methods. You might be able to adapt them to one more efficient query.
Also, if I haven't misunderstood what you want to achieve then your results should be similar to what a user would see in the resource tree in the manager when logged in?
That uses the resource/getnodes.class.php processor, which retrieves all possible resources for each context using getCollection, then loops through each and decides whether to display or not by using $resource->checkPolicy('list'). That might be another approach to consider.
I usually work with custom data rather than MODX resources so would be keen to hear how you get on with this.
I know this is really, really old, but I came across this question looking for the answer myself. After a bit more digging I've found that it's the access_resource_groups table that links document_groups and member_groups
document_groups.id = access_resource_groups.target
member_groups.id = access_resource_groups.principal

How to use Yii with a multilingual database model?

I’m having a problem getting the data from my database which I created to be completely multilingual, and I hope someone here can help me.
I’ve split up all my tables in 2 parts; the “universal” table (does not contain any text that needs to be translated) and the table which contains all the fields that need to be translated with their translations.
Example tables:
base_material
id
picture
base_material_i18n
base_material_id
localization_id
name
description
review_status
review_notes
localization
id
language_name
Query to get the translations (using English (en) as a fall-back language if there is no translation available):
SELECT o.id
, o.type
, o.code
, o.position
, ifnull(t.name,d.name) name
, ifnull(t.description,d.description) description
FROM base_material o
INNER JOIN base_material_i18n d
ON ( o.id=d.base_material_id)
LEFT OUTER JOIN base_material_i18n t
ON ( d.base_material_id=t.base_material_id AND t.localization_id='nl' )
WHERE d.localization_id='en'
My question is how I can automatically get those translations (with the fall-back language as in this query) attached to my model in Yii when I’m searching for the base_material objects? (This is only 1 example table, but almost all my tables (20+) are built in this way, so if possible I would be needing something flexible)
An example of an existing system using what I would need is Propel: http://propel.posterous.com/propel-gets-i18n-behavior-and-why-it-matters
Any ideas how to go about doing that? I’ve checked the existing Yii extensions regarding multilingual sites (like Multilingual Active Record), but they all use a different database design (general information+fall-back language in the main table, translations in the i18n table), and I’m not sure how to change those extensions to use my kind of DB model.
If someone knows of a way to change that existing extension so it can use my kind of DB scheme, then that would be absolutely brilliant and probably the best way to do this.
Edit: I've added a bounty because I still can't find anything on how to let Propel work with Yii (there does exist an extension for Doctrine, but Doctrine doesn't support this kind of DB model with translations either), nor any more information as to how to deal with this using an existing Yii extension or with scopes.
Edit: 98 times viewed but only 3 upvotes and 1 comment. I can't help feeling like I'm doing something wrong here, be it in my question or application/database design; either that or my problem is just very unique (which would surprise me, as I don't think my multilingual database design is that absurd ;-). So, if anyone knows of a better all-round solution for multilingual sites with Yii and/or Propel (apart from the current extensions which I really don't like due to the duplication of text fields) or something similar, please let me know as well.
Thanks in advance!
Have you tried http://www.yiiframework.com/extension/i18n-columns/ (based on http://www.yiiframework.com/extension/stranslateablebehavior/)?
It is an alternate, simpler, approach by adding new table fields in the style of {field}_{language code}, and then setting the translated field in the original model to the current language's translation on afterFind.
In essence, it will get you up and running with translatable fields with the translated content being fetched "automatically", for good and bad :). Adding and removing languages (=columns) is done using migrations.
I am also looking for a generic solution to implement i18n into Yii models.
Recently I chose a very similar database schema for a project like you.
The only difference is, that I am not using a separate language table, I store the language information in the i18n table.
The following solution is without a custom SQL statement, but I think this could be implemented with relation params, anyway, if you're working with foreign key in your database (eg. MySQL InnoDB) gii will create relations between your base_material and base_material_i18n table, like
class BaseMaterial extends CActiveRecord
public function relations()
{
return array(
'baseMaterialI18ns' => array(self::HAS_MANY, 'base_material_i18n', 'id'),
);
}
class BaseMaterialI18n extends CActiveRecord
public function relations()
{
return array(
'baseMaterial' => array(self::BELONGS_TO, 'base_material', 'id'),
);
}
Now you'd be able to access your translations by using the object notation for relations.
$model = BaseMaterial::model()->with('baseMaterialI18ns')->findByPk(1);
foreach($model->baseMaterialI18ns AS $translation) {
if ($translation->language != "the language I need") continue:
// do something with translation data ...
}
I thought about creating a behavior or base class for those models which would act a as helper for managing the translations - pseudo code:
I18nActiveRecord extends CActiveRecord
protected $_attributesI18n;
// populate _attributesI18n on query ...
public function __get($name) {
if(isset($this->_attributesI18n['language_I_need'][$name]))
return $this->_attributesI18n[$name];
else if(isset($this->_attributesI18n['fallback_language'][$name]))
return $this->_attributesI18n[$name];
else
parent::__get();
}
CActiveRecord __get() source
There is more work to be done to find the needed i18n record, also you could further limit the with() option to improve performance and reduce parsing on the PHP side.
But there may be different use cases how to determine the value, e.g. all translations, translation or fallback, no fallback (empty value).
Scenarios could be helpful here.
PS: I would be up for a github project!
You can try to use a simple multilingual CRUD extension.
it is very simple to use and modificate. you just need to add language field to your table.
just watch description here: http://all-of.me/yii-multilingual-crud/
it is in alpha state, but tried on a few projects. you can easily modificate it or contact author to fix or add features

Resources