我會實現這個使用Identifying Relationships和你的代碼的一些重構。
public class CarModel
{
[Key, Column(Order = 0), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
[Key, ForeignKey("Brand"), Column(Order=1)]
public int BrandId { get; set; }
public Brand Brand { get; set; }
}
有實施庫模式多種方式和我做了儘可能少的進行必要的修改,雖然我通常喜歡保存在一個層越往上的變化。
public class BrandRepository
{
private readonly Context context;
public BrandRepository(Context context)
{
this.context = context;
}
public void Add(Brand brand)
{
this.context.Brands.Add(brand);
}
public Brand FindByName(string name)
{
return this.context.Brands.Single(b => b.Name == name);
}
public void RemoveCarModel(Brand brand, string carModelName)
{
var carModelToRemove = brand.Models.Single(cm => cm.Name == "A car model");
brand.Models.Remove(carModelToRemove);
}
public void Save()
{
context.SaveChanges();
}
添加了一個測試,添加一個品牌與兩個車型,然後刪除其中一個車型。
[TestMethod]
public void Test()
{
// Arrange.
using (var context = new Context())
{
var models = new List<CarModel> {
new CarModel { Name = "A car model" },
new CarModel { Name = "Another car model" }
};
var brand = new Brand { Name = "A Brand", Models = models };
var brandRepository = new BrandRepository(context);
brandRepository.Add(brand);
brandRepository.Save();
}
// Act.
using (var context = new Context())
{
var brandRepository = new BrandRepository(context);
var brand = brandRepository.FindByName("A brand");
brandRepository.RemoveCarModel(brand, "A car model");
brandRepository.Save();
}
// Assert.
using (var context = new Context())
{
var brandRepository = new BrandRepository(context);
var brand = brandRepository.FindByName("A brand");
Assert.AreEqual(1, brand.Models.Count);
Assert.AreEqual("Another car model", brand.Models.Single().Name);
}
}
這是具體實施的問題。所以沒有代碼你的問題就沒有意義了。 –
增加了一些更詳細的問題。 –