I'm having two model Classes
public class Person
{
public int PersonId { get; set; }
public string Name { get; set; }
public int AddressId { get; set; }
public Address AddressInfo { get; set; }
}
public class Address
{
public int AddressId { get; set; }
public string streetName { get; set; }
public string City { get; set; }
public string State { get; set; }
}
If any value gets update in Person.AddressInfo.AddressId, update the Person.AddressId automatically. Kindly assist me how to update this in C#.
what about this?
public class Person
{
public int PersonId { get; set; }
public string Name { get; set; }
public int AddressId
{
get{ return AddressInfo?.AddressId ?? 0 }
set{ AddressInfo?.AddressId = value; }
}
public Address AddressInfo { get; set; }
}
public class Address
{
public int AddressId { get; set; }
public string streetName { get; set; }
public string City { get; set; }
public string State { get; set; }
}
This uses the AddressInfo as the back storage
You could simply write following into the Person class:
public int AddressId{
get{return this.AddressInfo?.AddressId ?? 0;}
set{this.AddressInfo?.AddressId= value;}
}
Or better to write:
public int? AddressId{
get{return this.AddressInfo?.AddressId;}
set{this.AddressInfo?.AddressId= value;}
}
below code can help you out,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
Address test = new Address();
test.AddressId = 0;
test.City = "xyzzzzzzzzzzzzzzz";
test.streetName = "xyz";
test.State = "xyzzzzzzzzzzzzzzzxxxxxxxxxxxxxxxxxxx";
Person ptest = new Person
{
PersonId = 1,
Name = "test1",
AddressInfo = test,
AddressId = 5,
};
}
}
public class Address
{
public int AddressId { get; set; }
public string streetName { get; set; }
public string City { get; set; }
public string State { get; set; }
}
public class Person
{
public int PersonId { get; set; }
public string Name { get; set; }
public int AddressId {
get{ return AddressInfo != null ? AddressInfo.AddressId : 0;}
set { AddressInfo.AddressId = value; }
}
public Address AddressInfo { get; set; }
}
}
Before assigning value to addressid ensure that addressinfo not null, if its null assign data to addressinfo then you can able to update the value, otherwise you will get object reference error.