[英]Entity Framework One-To-Many Delete relationship
I have two entities Transaction
and DiscountType
我有两个实体
Transaction
和DiscountType
Transaction: 交易:
public class Transaction
{
[Key]
public int TransactionID { get; set; }
public virtual DiscountType DiscountType { get; set; }
}
DiscountType: DiscountType:
public class DiscountType
{
[Key]
public int DiscountTypeID { get; set; }
public virtual ICollection<Transaction> Transactions { get; set; }
public float DiscountValue { get; set; }
public bool Enabled {get; set;}
}
Relationship: 关系:
modelBuilder.Entity<DiscountType>().HasMany(d => d.Transactions);
Aim: 目标:
I am trying to remove the relationship between the Transaction and the DiscountType, without actually removing either entity. 我试图删除事务和DiscountType之间的关系,而没有实际删除任何实体。
Problem: 问题:
Now I'm having no problem assigning a Discount to a transaction, but when I do the following: 现在我可以很方便地为交易分配折扣,但是当我执行以下操作时:
var transaction = context.Transactions.Where(t => t.TransactionID == 1).First();
transaction.DiscountType = context.DiscountTypes.Where(d => d.DiscountTypeID == 1).First();
context.SaveChanges();
var _transaction = context.Transactions.Where(t => t.TransactionID == 1).First();
_transaction.DiscountType = null;
context.SaveChanges();
It's quite a peculiar problem I'm having. 我遇到的是一个非常特殊的问题。 When this code is ran it does not remove the relationship between the two.
运行此代码后,它不会删除两者之间的关系。
Actual Code: 实际代码:
As you can see, even after the = null;
如您所见,甚至在
= null;
之后= null;
is executed, it still remains. 被执行,它仍然存在。
I think your select statement might need to be: 我认为您的选择声明可能需要是:
transaction.DiscountType =
context.DiscountTypes.Where(d => d.DiscountTypeID == 1).SingleOrDefault();
I think you better invert the relationship in the creation of the DbContext
: 我认为您最好在创建
DbContext
反转关系:
modelBuilder.Entity<Transaction>()
.HasOptional(x => x.DiscountType)
.WithOptionalPrincipal();
This creates a nullable foreign key to DiscountType in Transaction and I think it will allow you to set it to null
. 这将在Transaction中为DiscountType创建一个可为空的外键,我认为它将允许您将其设置为
null
。
(Personally I think it is a better way of putting it, because semantically it seems weird for a type to "have" Transactions, but a Transaction having a type is quite normal.) (我个人认为这是一种更好的放置方式,因为从语义上来说,类型“拥有”事务似乎很奇怪,但是具有类型的Transaction很正常。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.