Solved

Question about saving objects

Posted on 2011-02-17
11
264 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
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

What my article will show is if you ever had to do processing to a listbox without being able to just select all the items in it. My software Visual Studio 2008 crystal report v11 My issue was I wanted to add crystal report to a form and show…
Entering time in Microsoft Access can be difficult. An input mask often bothers users more than helping them and won't catch all typing errors. This article shows how to create a textbox for 24-hour time input with full validation politely catching …
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 tutorial demonstrates a quick way of adding group price to multiple Magento products.

932 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

16 Experts available now in Live!

Get 1:1 Help Now