I have been working with java and hibernate for many years, I am now starting working with C#, so I would like to do things more or less as I did in java.
I like annotations because I like to keep all configuration together with the entity.
I have two classes, city and country, city has a foreign key to country.
public class City {
[Key]
public long id { get; set; }
public long countryId { get; set; }
[ForeignKey("countryId")]
public virtual Country country { get; set; }
public string city { get; set; }
}
public class Country {
[Key]
public long id { get; set; }
public string country { get; set; }
public ICollection<City> Cities { get; set; }
}
I do not know if it is really needed to have to properties in city related to country (countryId
and country
) and if there is a way to have only the reference to the class
public Country country { get; set; }
Another question is that when I creates a new city
public class CityService:ICityService {
public City getCity(string cityTxt, Country country) {
City city = null;
using (var ctx = new Context()) {
city = ctx.Cities.Where(it => it.city == cityTxt && it.country.id == country.id).FirstOrDefault();
if (city == null) {
city = ctx.Cities.Add(new City { city = cityTxt, countryId = country.id });
ctx.SaveChanges();
}
}
return city;
}
}
I set the countryId
, after saving the new city, the city.country
is null, is there a way to populate the city.country
property? And if I set the countryId
and country
property
city = ctx.Cities.Add(new City { city = cityTxt, countryId = country.id , country = country });
After the ctx.SaveChanges()
a repeated instance of the country is created on database.
I am still migrating my java concepts to C#, so any good tutorial reference would be very appreciated (better if working with annotations instaid of Fluent API).
Thanks in advance.