Solved

Question about saving objects

Posted on 2011-02-17
11
267 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
AWS Certified Solutions Architect - Associate

This course has been developed to provide you with the requisite knowledge to not only pass the AWS CSA certification exam but also gain the hands-on experience required to become a qualified AWS Solutions architect working in a real-world environment.

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

How To Install Bash on Windows 10

Windows’ budding partnership with Canonical has certainly led to some great improvements. One of them being the ability to use Bash on your Windows machine without third party applications! This might be one of the greatest things a cloud engineer in a Windows environment can do!

Question has a verified solution.

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

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…
For most people, the WrapPanel seems like a magic when they switch from WinForms to WPF. Most of us will think that the code that is used to write a control like that would be difficult. However, most of the work is done by the WPF engine, and the W…
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…
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…

630 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