【发布时间】:2016-06-03 06:25:58
【问题描述】:
我已经使用 java 和 hibernate 多年,现在我开始使用 C#,所以我想做的事情或多或少像我在 java 中所做的那样。
我喜欢注释,因为我喜欢将所有配置与实体保持在一起。
我有两个班级,城市和国家,城市有国家的外键。
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; }
}
我不知道是否真的需要与国家相关的城市中的属性(countryId 和country),以及是否有办法只引用类
public Country country { get; set; }
另一个问题是当我创建一个新城市时
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;
}
}
我设置了countryId,保存新城市后,city.country为空,有没有办法填充city.country属性?如果我设置 countryId 和 country 属性
city = ctx.Cities.Add(new City { city = cityTxt, countryId = country.id , country = country });
在ctx.SaveChanges() 之后,会在数据库中创建一个重复的国家/地区实例。
我仍在将我的 java 概念迁移到 C#,因此非常感谢任何好的教程参考(如果使用 Fluent API 的注释更好)。
提前致谢。
【问题讨论】:
-
C# 中的属性应该使用 TitleCase。
-
@Gusdor 在 C# 中没有技术上的原因 - 但是,微软的指导方针很明确,应该这样做,每个人都这样做。我认识的每家公司都有接近微软的指导方针,它们都符合 CamelCase 属性命名
-
@Mafii 我想你的意思是
Title(或Pascal)案例。虽然CamelCase确实可以指代这种大小写(通常称为UpperCamelCase),但术语CamelCase通常指的是“第一个字母小写,其余单词大写”(likeThis)。 Even Microsoft refers toCamelCaseas the lowercase one :-) -
@Jcl 哎呀,但我希望它现在清楚我的意思
-
@KasparsOzols 那是你的意见,我同意。有些人可能不同意...
标签: c# entity-framework