简体   繁体   English

Entity Framework Core - 关系

[英]Entity Framework Core - relationship

I have 2 classes and I am looking for the best way to configure a relationship between them.我有 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; }

    }

At the moment when I create a new ride, a new address is created automatically.在我创建新行程时,会自动创建一个新地址。

How can I check if the address already exists in the database (by id), and if it does - navigate towards that address (not create a new one).如何检查该地址是否已存在于数据库中(通过 id),如果存在 - 导航到该地址(而不是创建一个新地址)。

I assume that your problem relates to incorrect entry state of address entities.我假设您的问题与地址实体的错误条目 state 有关。 You can use method TrackGraph to traverse all objects relates to newRide entity and change entry state to Unchanged if id exists:您可以使用 TrackGraph 方法遍历与 newRide 实体相关的所有对象,如果 id 存在,则将条目 state 更改为 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM