实体框架核心-关系

时间:2020-06-25 07:54:49

标签: c# .net entity-framework-core

我有2个课程,我正在寻找配置它们之间关系的最佳方法。

  public class Ride
    {
        public int Id { get; set; }
        public virtual Address StartPoint { get; set; }
        public virtual Address EndPoint { get; set; }
    }
    public class Address
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public decimal LocationLat { get; set; }
        public decimal LocationLng { get; set; }

    }

当我创建新游乐设施时,会自动创建一个新地址。

如何检查该地址是否已存在于数据库中(按ID),以及是否存在-导航至该地址(而不创建新地址)。

1 个答案:

答案 0 :(得分:0)

我假设您的问题与地址实体的错误输入状态有关。您可以使用TrackGraph方法遍历与newRide实体相关的所有对象,并在存在id的情况下将条目状态更改为Unchanged:

var newRide = new Ride();
newRide.StartPoint = new Address{...} //set Id property

context.Rides.Add(newRide);
context.ChangeTracker.TrackGraph(newRide, e => {
                                                if (e.Entry.IsKeySet)
                                                {
                                                    e.Entry.State = EntityState.Unchanged;
                                                }
                                                else
                                                {
                                                    e.Entry.State = EntityState.Added;
                                                }
                                            });
context.SaveChanges();