Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Question about saving objects

Posted on 2011-02-17
11
Medium Priority
?
269 Views
Last Modified: 2013-12-17
Hi experts,

I have a object _Login and I need save it. (line 6).
Then I created a new object _WLogin and I copied the _Login value. (line 7)
The problem is that, When I changed the properties of _WLogin, changed too the _Login properties of the. (Line 8)
The object _Login that not was changed, has a new value in _Login.LastLogin. (line 10)
What´s wrong?

Thanks.


1        public Login Logar(string Nome, string Senha)
2        {
3            try
4            {
5                PlexoEntities db = new PlexoEntities();
6                Login _Login = db.Login.FirstOrDefault(p => p.Nome == Nome && p.Senha == Senha);
7                Login _WLogin = _Login;
8                _WLogin.LastLogin= DateTime.Now;
9                Alterar(_WLogin);
10               return _Login;
11           }
12           catch (Exception ex)
13           {
14               PMensagem(this.ToString() + "\r\n" + ex.Message + "\r\n" + ex.InnerException);
15               return null;
16           }
17       }
18       #endregion
0
Comment
Question by:Plexo
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
11 Comments
 
LVL 42

Expert Comment

by:sedgwick
ID: 34916048
implement IClonable interface and override the Clone method of Login object, and replace line 7 to be:
Login _WLogin = _Login.Clone();

0
 

Author Comment

by:Plexo
ID: 34916141
Hi sedgwick,

How do I  implement IClonable interface?

Thanlks.
0
 
LVL 44

Expert Comment

by:Arthur_Wood
ID: 34966751
these lines:

6                Login _Login = db.Login.FirstOrDefault(p => p.Nome == Nome && p.Senha == Senha);
7                Login _WLogin = _Login;


are NOT doing what you think they are doing.

_WLogin is actually a copy of the REFERENCE to _Login, not a completely new 'copy' of the object itself.

_Login is a 'pointer' (also called a reference) to a location in memory.  _WLogin holds a copy of the same reference (a copy pointing to the same location in memory).

Where have you defined the Login class?  YOu need to look up the definition of the ICloneable interface, which describes a single method Clone.  A Clone of an object creates a completely NEW instance of the undelying class, and then assigns ALL of the properties of the original object to the corresponding properties of the new instance, then returns new Instance as the result of the Clone method.

AW
0
Prepare for your VMware VCP6-DCV exam.

Josh Coen and Jason Langer have prepared the latest edition of VCP study guide. Both authors have been working in the IT field for more than a decade, and both hold VMware certifications. This 163-page guide covers all 10 of the exam blueprint sections.

 
LVL 96

Expert Comment

by:Bob Learned
ID: 34969338
There is an example in the MSDN article about ICloneable:

ICloneable Interface
http://msdn.microsoft.com/en-us/library/system.icloneable.aspx

using System;
using System.Collections.Generic;
using System.Text;

namespace ICloneableTest
{
    class Student : ICloneable
    {
        private string firstName;
        private string lastName;
        private string regNo;

        public string RegNo
        {
            get { return regNo; }
            set { this.regNo = value; }
        }

        public string LastName
        {
            get { return lastName; }
            set { this.lastName = value; }
        }

        public string FirstName
        {
            get { return firstName; }
            set { this.firstName = value; }
        }

        public Student(string _firstName, string _lastName, string _regNo)
        {
            this.firstName = _firstName;
            this.lastName = _lastName;
            this.regNo = _regNo;
        }

        #region ICloneable Members

        public object Clone()
        {
            return this.MemberwiseClone();
        }

        #endregion
    }
}

===============================================
using System;
using System.Collections.Generic;
using System.Text;

namespace ICloneableTest
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create Student.
            Student student1 = new Student("abc", "pqr", "xyz");
            //Clone Student1.
            Student student2 = (Student)student1.Clone();
            //Here you can see it gives same value.
            Console.WriteLine("Before we change student1s first name");
            Console.WriteLine(student1.FirstName + " " + student2.FirstName);
            //By changing one objects property, you can understand they are not same reference.
            student1.FirstName = "ABC";
            Console.WriteLine("After we changed student1s first name");
            Console.WriteLine(student1.FirstName + " " + student2.FirstName);
            Console.Read();
        }
    }
}

Open in new window


MemberwiseClone is a protected inherited from the System.Object class, so it is only available to inheriting classes, and can only do light-weight cloning, which doesn't include reference cloning.  For that you would need to look into deep-cloning.

Fundamentals: Deep Cloning In C#
http://www.thereforesystems.com/fundamentals-deep-cloning-in-c/
0
 

Author Comment

by:Plexo
ID: 34970540
Hi Arthur_Wood.

I didn´t define Login Class. It is a Entitie, defined in PlexoModel.edmx.

Thanks.
0
 

Author Comment

by:Plexo
ID: 34970571
Hi TheLearnedOne.

Como a minha classe Login é uma entidade eu não consegui usar o exemplo.
Parece que o exemplo seria para uma classe Login criada manualmente.

Thanks.
0
 
LVL 96

Accepted Solution

by:
Bob Learned earned 2000 total points
ID: 34970631
I really appreciate Google Translate!!

Loose translation:
As my Login class is an entity I could not use the sample.  It seems that the example would be for a Login class created manually.

The Login class is a partial class, which means that you can define another partial Login class with your implementation of the Clone, and to implement ICloneable:

public partial class Login : ICloneable
{

        #region ICloneable Members

        public object Clone()
        {
            return this.MemberwiseClone();
        }

        #endregion

}

Open in new window

0
 

Author Comment

by:Plexo
ID: 34970777
Hi TheLearnedOne.

Excuse me. I copied the wrong part of the translator!
0
 

Author Comment

by:Plexo
ID: 34980591
Hi TheLearnedOne.

How I´m using Entity Framework, my difficulty was to understand where it should be placed the public partial class Login: ICloneable.
Just to record for future references, it should be placed in the EntityModel.Designer.cs before the end of region Primitive Properties.

Thanks

0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…

722 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question