Skip to content

Instantly share code, notes, and snippets.

@3bdNKocY
Created March 28, 2015 17:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 3bdNKocY/7f87691e0a3b7d19b7bc to your computer and use it in GitHub Desktop.
Save 3bdNKocY/7f87691e0a3b7d19b7bc to your computer and use it in GitHub Desktop.
public class VivendaContext : DbContext
{
public DbSet<Premise> Premises { get; set; }
public DbSet<Person> Persons { get; set; }
public DbSet<PremiseType> PremiseTypes { get; set; }
public DbSet<RentContract> RentContracts { get; set; }
public DbSet<BuyContract> BuyContracts { get; set; }
public DbSet<Property> Properties { get; set; }
public DbSet<Address> Addresses { get; set; }
public DbSet<Town> Towns { get; set; }
public DbSet<Meter> Meters { get; set; }
public DbSet<Counter> Counters { get; set; }
public DbSet<CounterReading> CounterReadings { get; set; }
private static VivendaContext _Current;
public static VivendaContext Current
{
get
{
if (_Current == null)
{
_Current = new VivendaContext();
}
return _Current;
}
}
protected VivendaContext()
{
LoadTowns();
}
private void LoadTowns()
{
if (Towns.ToList().Count == 0)
{
var xml = XDocument.Load("DataModels/postalCodes.xml");
var towns = from data in xml.Element("Codes").Elements("Code")
select new Town
{
Name = this.NormalizeName(data.Element("Row").Attribute("Name").Value),
PostalCode = data.Element("Row").Attribute("Code").Value
};
foreach (var town in towns)
{
Towns.Add(town);
}
this.SaveChanges();
}
}
private string NormalizeName(string name)
{
if (name.ToUpper(CultureInfo.InvariantCulture) == name)
{
return name.First().ToString().ToUpper() + name.Substring(1).ToLower();
}
return name;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Premise>().HasMany(p => p.Meters).WithRequired(m => m.Premise);
modelBuilder.Entity<Meter>().HasMany(c => c.Counters)
.WithRequired(r => r.Meter)
.WillCascadeOnDelete();
modelBuilder.Entity<Counter>().HasMany(c => c.Readings)
.WithRequired(r => r.Counter)
.WillCascadeOnDelete();
}
public bool IsAddressOccupied(Address address)
{
return
this.Addresses.FirstOrDefault(
a =>
a.AddressId == address.AddressId
|| a.Number == address.Number
&& a.NumberExtension == a.NumberExtension
&& a.Street == address.Street
&& a.Town.Name == address.Town.Name
&& a.Town.PostalCode == address.Town.PostalCode
) != null;
}
public static void Save()
{
Current.SaveChanges();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment