0

我有 3 节课:

public class User
{
    ...
    public List<SerialHistory> SerialHistory { get; set;}
    ...
}

public class SerialHistory
{
    ...
    public DateTime DateAdded { get; set; }
    public SerialNumber SerialNumber { get; set; }
    ...
}

public class SerialNumber
{
    ...
    public User User { get; set; }
    ...
}

我真的很喜欢这样,当我这样做时:

user.SerialHistory.Add(new SerialHistory { 
                                            SerialNumber = serialNumber, 
                                            DateAdded = DateTime.Now 
                                         });

会自动分配给它serialNumber.Useruser

这是可能的还是超出了 EntityFramework 的能力?

4

1 回答 1

1

No, there is no special option in Entity Framework to ensure this. User.SerialHistory and SerialNumber.User are navigation properties of two different relationships. What you have is a special business logic that cannot be enforced by a foreign key relationship in the database, hence it cannot be enforced by any mapping (that basically just represents foreign key relationships) with Entity Framework.

Your best option is maybe a special method of User:

public void AddSerialNumber(SerialNumber serialNumber)
{
    serialNumber.User = this;
    SerialHistory.Add(new SerialHistory { 
                                            SerialNumber = serialNumber, 
                                            DateAdded = DateTime.Now 
                                        });
}
于 2013-04-12T21:29:33.927 回答