Entity Framework : A short way to copy one object with it's child to a new object ?

Hello !
I'm using entity framework 6.
Sometimes I need to copy an existing object with all its childs to a new object and to save to database.
I'm using a standart way by creating a new object , copy one by one it's properties from existing object ( except the ID ) , after I create new object for every child and copy one by one each properties except the ID and Parent id......
But of course this is a hard way to do especially when the object have a lot's of properties.
I want to know is there any short way  ( built in) to do this ?
Thank you !

Actually , I'm using this extension :
Imports System.ComponentModel
Imports System.Collections
Imports System.Data.Entity.Core.Objects.DataClasses
Imports System.Runtime.Serialization
Imports System.IO
Imports System.Reflection
Module Extensions
<System.Runtime.CompilerServices.Extension> _
Public Function Clone(Of T As EntityObject)(source As T) As T
Dim ser = New DataContractSerializer(GetType(T))
Using stream = New MemoryStream()
ser.WriteObject(stream, source)
stream.Seek(0, SeekOrigin.Begin)
Return CType(ser.ReadObject(stream), T)
End Using
End Function
<System.Runtime.CompilerServices.Extension> _
Public Function ClearEntityReference(source As EntityObject, bCheckHierarchy As Boolean) As EntityObject
Return source.ClearEntityObject(bCheckHierarchy)
End Function
<System.Runtime.CompilerServices.Extension> _
Private Function ClearEntityObject(Of T As Class)(source As T, bCheckHierarchy As Boolean) As T
If source Is Nothing Then
Throw New Exception("Null Object cannot be cloned")
End If
Dim tObj As Type = source.[GetType]()
If tObj.GetProperty("EntityKey") IsNot Nothing Then
tObj.GetProperty("EntityKey").SetValue(source, Nothing, Nothing)
End If
If Not bCheckHierarchy Then
Return CType(source, T)
End If
Dim PropertyList As List(Of PropertyInfo) = (From a In source.[GetType]().GetProperties() Where a.PropertyType.Name.Equals("ENTITYCOLLECTION`1", StringComparison.OrdinalIgnoreCase) Select a).ToList()
For Each prop As PropertyInfo In PropertyList
Dim keys As IEnumerable = CType(tObj.GetProperty(prop.Name).GetValue(source, Nothing), IEnumerable)
For Each key As Object In keys
Dim childProp = (From a In key.[GetType]().GetProperties() Where a.PropertyType.Name.Equals("EntityReference`1", StringComparison.OrdinalIgnoreCase) Select a).SingleOrDefault()
childProp.GetValue(key, Nothing).ClearEntityObject(False)
key.ClearEntityObject(True)
Next
Next
Return CType(source, T)
End Function
End Module
But the problem is that when I try to use like this :
Dim litm, newitm as MyObject
For Each litm In itemlist
newitm = litm.Clone()
newitm.ClearEntityReference(True)
context.MyObjects.Add(newitm)
Next
context.SaveChanges()
I get an error :
Public member 'Clone' on type 'MyObject' not found.

Similar Messages

  • Problem Entity framework and short types

    I am using the Entity Framework in Visual Studio to access a table in my oracle database. Problem is when selecting a record in runtime the following error shows up:
    Value was either too large or too small for an Int16
    This error originates when trying to access a table-field declared as number(5). The framework translates this in a short field. The max value for short is 32767, but the value in the table is 36001.
    Can I solve this?
    thanks.

    Yes, you need to change the mapping for that type to an int32. To do that you can add this to your configuration file:
    <oracle.dataaccess.client>
    <settings>
    <add name="int16" value="edmmapping number(4,0)" />
    <add name="int32" value="edmmapping number(9,0)" />
    </settings>
    </oracle.dataaccess.client>
    You should then update the model to get the new changes. Note that I've found that I have to change the types manually in the model, but after I do that once it works fine. Documentation is here: http://docs.oracle.com/cd/E11882_01/win.112/e18754/featLINQ.htm

  • Entity framework-calling stored Proc to return one param returns ORA-6550

    Hi There,
    I am new to the VS2010/MVC3 game with ODP.net, so no abuse please .......
    I have successfully inserted a record into a table via the controller/entity framework, but only by currently hard coding the id. The next logical step is to attempt to obtain the id from the Oracle DB via a stored procedure. Here is the body of the PL/SQL procedure on the Oracle side:-
    create or replace package body dotnetcommon as
    PROCEDURE getnextpoid ( p_to_id OUT NUMBER ) IS
    BEGIN
         SELECT pord_seq.nextval INTO p_to_id FROM dual;
    END getnextpoid;
    end dotnetcommon;
    show error
    I have then added this procedure to my Entity Framework Model within VS2010 , and from within the Model Browser, I now have a stored procedure of "DOTNETCOMMON_GETNEXTPOID" under my Model.Store. This has an out type parameter named p_to_id, which is a type of number.
    I then added a function import, so I have a function by the name of "GETNEXTPOID" under the Function Imports folder, with a collection property of 'None'.
    This function has a parameter P_TO_ID with a type of "Decimal".
    From within my controller, I have the following code:-
    [HttpPost]
    public string Create(PURCHASEORDER po)
    TasEntities tmprep = new TasEntities();
    ObjectParameter poid = new ObjectParameter("poId", typeof(Int16));
    var result = tmprep.GETNEXTPOID(poid);
    return "Next PO Id is " + result;
    Thus, on pressing the Save from my view, i am hoping to return the next logical sequence number into the poid objectparameter. However, I am presented with the following error:-
    Inner Exception of:-
    {"ORA-06550: line 1, column 8:\nPLS-00306: wrong number or types of arguments in call to 'GETNEXTPOID'\nORA-06550: line 1, column 8:\nPL/SQL: Statement ignored"}
    It falls over , taking me to the Model.Designer.cs at :-
    public int GETNEXTPOID(ObjectParameter p_TO_ID)
    return base.ExecuteFunction("GETNEXTPOID", p_TO_ID);
    I am assuming it is to do with the decimal/int/number conversion, but I do not have the nouse to fix it ? Does anybody know what is wrong with what I have attempted to do above ?
    Please please get back to me if you need any more information, I am wanting to move on but cannot.
    I have seen posts regarding setting the sequence in a before insert trigger on the table, but this is not ideal. Can the above not work instead ?
    Many thanks in advance for any help you can provide.
    Graeme
    Edited by: user4487499 on 05-Apr-2011 08:18

    I have now raised this in the odp.net forum, as on looking at other posts it seems to be the best place for it.
    Cheers,
    Graeme
    Edited by: user4487499 on 05-Apr-2011 08:18
    Edited by: user4487499 on 05-Apr-2011 13:00

  • SqlPlus or PL/SQL -- how to copy one procedure with one command?

    Hello,
    In this scenario, I have 11g on server1 and server2.
    Using SqlPlus or a PL/SQL procedure, I want to issue a command to copy a procedure now on server1 over to a new identical server and tablespace called server2.
    Would someone please help me with the syntax of this copy command?
    On server2 I tried something like this:
    create procedure tablespace1.procname from tablespace1.procname@dblink_server1
    Note that I want to avoid using imp or datapump, etc. I want this to be a simple copy of one procedure by name from another server.
    Any suggestions are greatly appreciated. Thank you.

    Thank you.
    Below, line 1 method returns a 'create table...' statement:
    1> select dbms_metadata.get_ddl ('TABLE','table_name','schema_name') FROM dual
    This works well, especially for tables, but I still cannot figure out how to do it across a database link.
    The next method, line 2, works well for procedures, but not for tables:
    2> select name, type, line, text from user_source where type='PROCEDURE' ORDER BY NAME,LINE
    One way or another, I am trying to get the source from selected remote servers and then use it to create the same objects on other remote servers.
    Any suggestions are greatly appreciated.
    Live long and prosper.

  • What is the best way to copy 700 local folders full of email to a new computer?

    I am moving my wife from and old computer (Thunderbird, Win XP) to a new one (Thunderbird Win 7). She has about 700 local folders with thousands of email messages in them. What is the best way to copy them to the new computer?

    The easiest way is just copy the whole profile.
    Help menu > troubleshooting information
    Close Thunderbird
    In windows explorer select all and copy.
    paste everything onto a thumb or other read/write portable media (not CD or DVD)
    on the new Machine repeat the troubleshooting and close steps to get the current profile folder
    This time paste everything from the portable media into the profile replacing what is there
    Open Thunderbird, your done mail contacts add-ons everything

  • Is there any way to open a file with a .msi extension on my new mac?

    I have Camtasia from the pc I was using. It has a .msi file extension for the installation file. Is there any way to open the Camtasia installation file with the .msi extension on my new Mac?
    Thanks,
    Jerry

    That's a Microsoft program which requires Windows. You could run on your Mac if you install Windows on it.
    Windows on Intel Macs
    There are presently several alternatives for running Windows on Intel Macs.
    Install the Apple Boot Camp software.  Purchase Windows 7 or Windows 8.  Follow instructions in the Boot Camp documentation on installation of Boot Camp, creating Driver CD, and installing Windows.  Boot Camp enables you to boot the computer into OS X or Windows.
    Parallels Desktop for Mac and Windows XP, Vista Business, Vista Ultimate, or Windows 7.  Parallels is software virtualization that enables running Windows concurrently with OS X.
    VM Fusion and Windows XP, Vista Business, Vista Ultimate, or Windows 7.  VM Fusion is software virtualization that enables running Windows concurrently with OS X.
    CrossOver which enables running many Windows applications without having to install Windows.  The Windows applications can run concurrently with OS X.
    VirtualBox is a new Open Source freeware virtual machine such as VM Fusion and Parallels that was developed by Solaris.  It is not as fully developed for the Mac as Parallels and VM Fusion.
    Note that Parallels and VM Fusion can also run other operating systems such as Linux, Unix, OS/2, Solaris, etc.  There are performance differences between dual-boot systems and virtualization.  The latter tend to be a little slower (not much) and do not provide the video performance of the dual-boot system. See MacTech.com's Virtualization Benchmarking for comparisons of Boot Camp, Parallels, and VM Fusion. A more recent comparison of Parallels, VM Fusion, and Virtual Box is found at Virtualization Benchmarks- Parallels 10 vs. Fusion 7 vs. VirtualBox. Boot Camp is only available with Leopard and later. Except for Crossover and a couple of similar alternatives like DarWine you must have a valid installer disc for Windows.
    You must also have an internal optical drive for installing Windows. Windows cannot be installed from an external optical drive.

  • Is there an easy way to copy one attribute value to another in same VO?

    Hi All,
    I have two attributes Total and Sum in my masterVO (based on masterEO). Sum is transient attribute which calculates the sum of costs from detailVO. Now I want to pass the value from Sum to Total so that Total can have the right value to insert into DB. In VORowImpl file I tried to set the value in the getter method of Total (code below) but it ends in dead loop. Wonder what's the right way for me to do then?
    Thanks,
    Sophy
    public BigDecimal getTotal() {  
    setTotal(getSum());
    return (BigDecimal) getAttributeInternal(TOTAL);
    Edited by: user10366631 on Mar 2, 2012 11:58 AM

    Thanks for asking, Timo. In my case we already have this totalCost attribute in the DB table which will be used by others. Whenever user changes a cost in the detailVO from UI, I need to recalculate the totalCost in masterVO and insert it into DB. Hence values in the DB will always match.
    I found the way of passing the value of attribute though, whic is code below. Hope it'll help someone else looking for similar problem solution...
    public BigDecimal getSumCost() {
    if ((BigDecimal)getAttributeInternal(SUMCOST) != this.getTotalCost())
    this.setTotalCost((BigDecimal)getAttributeInternal(SUMCOST));
    return (BigDecimal)getAttributeInternal(SUMCOST);
    }

  • Is there any way to copy a photo with Lightroom adjustments without making a separate copy?

    I do most of my printing from lightroom. I generally set up my image the way I want it for printing on photo paper, and then I make other copies and adjustments for printing on things like Canvas, coffee cups, tiles, etc.
    The problem I have is I set up templates in photoshop, say for a coffee cup, which will have the correct dimensions, perhaps some text, etc. To get to the lightroom photo with the lightroom adjustments I have to "edit a copy with lightroom adjustments" in photoshop, then copy and paste the image to the template in photoshop. Now I have another copy of the image on my harddrive and in lightroom. So after I copy the image in photoshop, I close it go back to lightroom and delete the copy I just made. Besides the extra fragging on the harddrive this creates, I know I am setting myself to delete the wrong photo by accident through repetition, and it is extra work.
    How can get a copy of a photo with Lightroom adjustments to the clipboard without making another physical copy of the photo?
    Any suggestions would be appreciated.
    Godspeed,
    Bruce

    I may not be the best resource for tiles and cups, I've just started printing to them. Basically I'm doing them using an epson printer with dye sublimation inks printing on transfer paper and then doing the transfer at 400 degrees with a press. I wanted to be able to do my own to get the cost down, and wanted to be able to make it actually usable, (dishwasher safe, etc) so this is the best route I've found. I had to get a new printer, 2 presses, a bulk ink system, and the supplies to print on so it is a pretty hefty up front expense. It can be done cheaper though using a mug wrap heated in an oven (not your cooking oven though). I worked with the folks at Conde to get set up, and they seem pretty good. But I'm still early in the learning curve, so I would be able to tell you a lot more in 6 months.

  • Is there a way to have one workspace with two monitors?

    In Maverick is there a way to return to the system were you have 1 workspace and two monitor? Where at present there is this tendency for applications to auto hide partially.

    Yes it is, my bad. I'm running an external display myself and have that setting. I saw the preference with the checkmark and wrote that one by mistake.

  • Is there any way to copy the music from my Ipod touch to my new laptop?

    I just want to transfer the songs from my Ipod to the ITunes on my laptop. I have obtained songs form various sources other than iTunes and its only showing the songs ive bought from iTunes. Is there any way to easily transfer all the songs?

    You'll have to use 3rd party software, check this article:
    User Tip: Syncing to a "New" Computer or replacing a "crashed" Hard Drive

  • Is there a way to completly copy one hd onto the other?

    I have a hd that I want to backup immediatly because it is giving me all the signs that it might die soon.. is there an easy way to copy one of them onto the other? since just clicking on one and draging the stuff into the other leaves the invisable files behind. when i mean copy I mean clone them. please help before my dieing HD croaks. thanks
    powermac dual 2.7 G5, imac G4 800mhz, emac 1ghz, dual 2ghz powermac   Mac OS X (10.4.3)  

    If you are using OS X 10.3.8 or later (including 10.4.x), you can use the OS's built in disk tool Disk Utility to create a copy or clone of your hard drive.
    Launch Disk Utility, located in /Applications/Utilitities/. In Disk Utilities select your original drive. Click the tab labeled Restore, then drag your original hard drive from the left hand list, to the field labeled Source. Drag the hard drive you want to use as a copy to the field labeled Destination. Click the Restore button, and Disk Utility will copy everything from the Source drive to the Destination drive, and will also make the destination drive bootable, assuming the source included a system and was bootable.
    Thats it, no separate software needed.
    Tom N.

  • Deploying LightSwitch applications to IIS using the Oracle Entity Framework

    I have had no sucess running Lightswitch applications on IIS using the Oracle Beta entity framework. Applications work fine from visual studio but after deployment fail when I trying to access an Oracle data entity.
    I have tried deploying to a 2008 V2 server 64Bit running IIS7.5 and also to a 32 bit windows 7 machine running IIS7. Both machines had the entity framework installed and I could connect to Oracle with SQL developer just fine. Briefly in the case of the 64 bit machine I get a bad image exception indicating a 64/32 bit conflict. (App pool switched to allow 32bit). The problem with the 32Bit machine is that the session either hangs or dies with an [Arg_TargetInvocationException]
    In all tests apps could connect to SQL server fine but as soon as I use an Oracle connection they fail. It would very helpfull if someone could confirm that they have managed to use the Entity framework Beta with Lightswitch and IIS.
    Thanks in advance
    Edited by: user12218662 on 08-Oct-2011 11:35
    Edited by: user12218662 on 08-Oct-2011 11:37

    Both hosts working now. Initially I created a service account for the aspnet service with extended rights and assigned this to the application pool. This subsequentluy turned out not to be required - ApplicationPoolIdentity works fine. What worked was as follows:
    1. On a 64 Bit host you need to set the application pool to Enable 32 Bit Applications (Right click the relevant app pool in IIS and select advanced)
    2. Switch off windows authentication for the application (leaving just anonoymous authentication) This was required on both hosts
    3. On the 32 Bit host copy tnsnames to the oracle client admin folder - the framework seems to ignore theTNS_ADMIN environment variable. Probably more to this but its working for now.

  • Copying one users calendar to anothers

    I'm kinda new to this whole Palm thing and not real computer knowledgable in general, so please forgive my ignorance in something that's probably really simple for most of you to figure out.
    We have a 2 person office and both our computers are networked. I was wondering if there is a way to copy one network users calendar to the others in its entirety. Not a whole year, but one month. We are continually sending each other emails with a V attachment in it so that we are able to know each others schedule and we can update our calendars. Either that or one of us has to run into the others office to look at their calendar so that we don't double schedule 2 different events at the same time and date. I can see the other users calendar through the network if he isn't accessing it at the time, but I'd like to be able to copy his calendar so I can paste it into mine.
    Is this possible?
    Thanks!
    chaikwa.
    Post relates to: Palm TX
    This question was solved.
    View Solution.

    The real only choice you would have in order not to complicate things is to export the entire calendar from one computer and import it into the other computers Palm desktop. If you export just the range of dates in the calendar for 1 month instead of the entire calendar, it will only import the month exported and will not have the entire year on the 2nd computer.
    Have you considered printing out the calendar from Palm desktop?  This might be an easier way to compare calendars and then making adjustments in Palm desktop.
    Click on the following link for instructions regarding printing the calendar in Palm desktop.
    http://www.palm.com/cgi-bin/cso_kbURL.cgi?ID=35451
    Post relates to: Palm i705

  • How to Copy one CD to another CD

    Hi: I want to copy a non-copyrighted music CD to a blank CD to that I can have a CD copy of the original music CD.
    I have a Mac Mini Intel, Solo, 1.5GZ, Running Tiger 10.4.11, which I upgraded to 2Gigs of ram.
    I know there must be an easy way to copy one music CD to a blank CD, but for the life of me I can't figure it out. Thanks very much. Jerry.

    Thanks so much, Fortuny and Awfers. I haven't had a chance to use SimplyBurns yet and I plan to try it, but I was able to import the CD into ITunes and follow the directions Awfers gave. I really appreciate your help. Best wishes, Jerry.

  • Server 10.5 crashed -- any way to copy settings/preferences from old HD?

    My 10.5 Server PowerMac died. Tried a manual 'archive and install' by moving system files to "Previous" folder using Terminal, installing on top, but that didn't work. I still have an image of the old HD -- is there any way to copy the relevant system or preference files to the new installation to get this Server back online?
    Any help or tips appreciated!
    Thanks,
    -Brian

    if u r goin to format ur hdd u hav 2 backup 2 things......
    one is ur mail folder(user/library/mail) and com.apple.mail.plist(user/library/preferences/com.apple.mail.plist)
    make a copy of these files and then no worries - all ur mails and mail settings will be safe. after formatting u dont have to reconfigure ur mail, just copy and paste mail.plist to preferences folder (replace it) and if all mails are not showing up import ur mail folder.
    saving network plist wont help......

Maybe you are looking for

  • Final Cut Server Usage Question...

    I have just started researching this product and confused a little about it. I am the IT dept at a small advertising agency that does quite bit of video work. Mostly all of the workstation in the office are PowerMac G5's that clock in at dual 2.2GHz

  • Wbs element can no longer be shifted error while creating wbs

    i am trying to create wbs with bapi_project_maintain, i am facing an error with message no 418 WBS element 1899-CAP-10-100-001-1507 can no longer be shifted

  • ALE : Error msg 'Application not posted'

    Hello all, when i send master data from sender to receiver then at recaiver side it shows the error like  'Application not posted'. what it means ? I have checked all the connection for both system.Remote connection is also working.IDOC generated at

  • How to read mutiple excel columns from clipboard and populate table control

    Hi All, I have a requirement to populate two columns in table control from excel using clipboard. (Copy two columns from excel and then, click on a button on the screen and table control's two columns should be filled). I am using FM CLPB_IMPORT to g

  • Prevent SWF from caching?

    Hi. I have a problem here, I've been searching on google and through forums for hours now trying to find a way to prevent my site from cache in browsers. I know it's not possible to "prevent" it from caching, but it's a way to trick the browser into