Tuesday, May 13, 2014

Using LINQ to Add and Get associated entities (C#)

Hi,
 if you have an Entity Database Model with two tables associated with foreign key and you need to add and then get records  using LINQ here is an example.
Entity „Apartments” contains information about apartments in a house. Each apartment can have a electricity meters (1 or more). In the example, tables have 1 to many relationship, as you can see on the picture above.


 Add record to both tables  with function „AddApartment()”:
MyDBContext dbContext = null;
       
public void AddAppartment(string apNumber, int ownerId, int regPeopleCount, int houseId, int electricityMetrics)
        {
            dbContext = new MyDBContext();
            Apartments newApartments = new Apartments();
            newApartments.ApartNumber = apNumber;
            newApartments.ApartOwnerId = ownerId;
            newApartments.HousesId = houseId;

            ElectricityMeters newElectricityMeters = new ElectricityMeters();
            newElectricityMeters.MeterNumber = electricityMetrics;
            newElectricityMeters.VerificationDate = DateTime.Now;
            newElectricityMeters.Apartments = newApartments;
           
            dbContext.Apartments.Add(newApartments);
            dbContext.ElectricityMeters.Add(newElectricityMeters);
           
            dbContext.SaveChanges();
        }

To get all records from both table you can use the „GetApartments()”
public List<ElectricityMeters> GetApartments()
        {
            dbContext = new MyDBContext();
            var someList = dbContext.ElectricityMeters.Include("Apartments").ToList();
            return someList;


        }

Have a good day :)