gpt4 book ai didi

c# - EF6 - 在单个事务中保存更改后虚拟属性未保存到数据库

转载 作者:行者123 更新时间:2023-11-30 23:09:27 24 4
gpt4 key购买 nike

我按照以下方式设置了 3 个实体。

public class Person
{
[Key]
public int PersonId { get; set; }
public virtual ICollection<Location> Locations { get; set; }
}

public class Location
{
[Key]
public int LocationId { get; set; }
public int PersonId { get; set; }

public virtual Person Person { get; set; }
public virtual ICollection<Value> Values{get; set; }
}

public class Value
{
[Key]
public int ValueId { get; set; }
public int LocationId { get; set; }

public virtual Location Location { get; set; }
}

使用 Fluent Api,我设置了从 Location 到 Person 以及从 Value 到 Location 的外键配置。

        // Person to Location(s)
modelBuilder.Entity<Person>()
.HasMany(e => e.Locations)
.WithRequired(e => e.Person)
.WillCascadeOnDelete(true);

// Location to Value(s)
modelBuilder.Entity<Location>()
.HasMany(e => e.Values)
.WithRequired(e => e.Location)
.WillCascadeOnDelete(false);

我想做的是创建一个新人,添加一个位置,然后向该位置添加一个值。

所以自然要先造人

[pseudo code]
var newPerson = new Person();

然后创建位置

[pseudo code] 
var newLocation = new Location { Person = newPerson };

最后是值

[pseudo code]
var newValue = new Value { Location = newLocation };

DbContext.Values.Add(newValue);DbContext.SaveChanges();

发生的事情是,如果我愿意,我可以成功地用新创建的人保存位置,但是当我尝试降低另一个级别并添加上面的值时,它提示值和位置之间的外键约束.

我已经设法通过首先将 Location 添加到上下文并保存更改来让它工作,但这意味着我的代码不是事务安全的。

最佳答案

您能够保存这个人,因为它不包含外键,这意味着它没有 Locationid 的属性,但在值的情况下,它需要 Locationid,这是定义关系的全部目的。

当你定义两个表之间的关系时,你根本无法避免在没有另一个表的外键的情况下将记录保存在一个表中。添加位置,保存更改,在下一行中添加您的值,然后保存更改。此过程不会使您的应用程序以任何方式受到攻击。

如果您仍然不想这样做,那么不要定义与 Entity Framework 的关系,而是让 Locationid 在您的值表中唯一并自行执行自定义验证,但我不建议这样做。

关于c# - EF6 - 在单个事务中保存更改后虚拟属性未保存到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45816494/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com