我正在尝试保存具有OneToMany关系的模型。当我在Cascade.All()
映射中添加HasMany
时,如果父级有子级,则在保存父级时遇到错误。
我的错误:
Batch update returned unexpected row count from update; actual row count: 0; expected: 1;
我的模型:
public class BaseModel
{
public virtual Guid Id { get; set; }
}
public class NamedModel : BaseModel
{
public virtual string Name { get; set; }
}
public class Ingredient : NamedModel
{
public virtual int Amount { get; set; }
public virtual Recipe Recipe { get; set; }
}
public class Recipe : NamedModel
{
public virtual IList<Ingredient> Ingredients { get; set; }
}
我的映射:
public BaseMapping<TModel> : ClassMap<TModel> where TModel : BaseModel
{
public BaseMapping()
{
Id(x => x.Id).GeneratedBy.Guid();
}
}
public IngredientMapping : BaseMapping<Ingredient>
{
public IngredientMapping()
{
Map(x => x.Name);
Map(x => x.Amount);
References(x => x.Recipe).Column("Recipe");
}
}
public RecipeMapping : BaseMapping<Recipe>
{
public RecipeMapping()
{
Map(x => x.Name);
HasMany(x => x.Ingredients).KeyColumn("Recipe").Inverse().Cascade.All();
}
}
我的代码:
public static void Main(string[] args)
{
var recipe = new Recipe {
Name = "Recipe"
};
var ingredient = new Ingredient {
Name = "Ingredient",
Amount = 1,
Recipe = recipe
};
recipe.Ingredients = new List<Ingredient> { ingredient };
...
session.Save(recipe);
transaction.Commit(); // Error in this line
}
我的映射可能与某件事有关,因为当我保存不含任何成分的配方时,一切正常。
我认为问题在于,nhibernate在保存父项之前会尝试保存成分,这会导致错误,因为Recipe
与有效的食谱ID不匹配。但是我真的不知道如何解决它。