Solved

Question about saving objects

Posted on 2011-02-17
11
263 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
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
 
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
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 

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 500 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

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Recently while returning home from work my wife (another .NET developer) was murmuring something. On further poking she said that she has been assigned a task where she has to serialize and deserialize objects and she is afraid of serialization. Wha…
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…
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…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

757 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

Need Help in Real-Time?

Connect with top rated Experts

25 Experts available now in Live!

Get 1:1 Help Now