我一直在努力删除具有多对多关系的实体。我现在有以下代码可以使用,但我的直觉告诉我,我对此完全没错。
对我来说最强烈的指标之一是,只有在Relations.cs中创建AccountID和BrokerID Nullable时,以下代码才有效。如果我不使AccountID和BrokerID Nullable我只删除'关系'实体并在删除'帐户时出错实体。
有人可以告诉我,我是否在正确的轨道上?我认为我可以删除一个实体,而不是我现在正在做的工作,同时更有效地使用EF6。
我在EF6中使用数据库优先方法。 这是我正在使用的一些代码。
Accounts.cs:
public partial class Accounts
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Accounts()
{
this.Relations = new HashSet<Relations>();
}
public int AccountID { get; set; }
public string AccountName { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Relations> Relations { get; set; }
}
Brokers.cs
public partial class Brokers
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Brokers()
{
this.Relations = new HashSet<Relations>();
}
public int BrokerID { get; set; }
public string BrokerName { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Relations> Relations { get; set; }
}
Relations.cs
public partial class Relations
{
public int RelationID { get; set; }
public Nullable<int> AccountID { get; set; }
public Nullable<int> BrokerID { get; set; }
public Nullable<System.DateTime> RelationStartDate { get; set; }
public virtual Accounts Accounts { get; set; }
public virtual Brokers Brokers { get; set; }
}
删除实体..
using (DbEntities db = new DbEntities())
{
var t = (from d in db .Relations
where d.RelationID == relationID
select d).Single();
db.Relations.Remove(t);
db.SaveChanges();
}
using (DBEntities db = new DBEntities())
{
var t = (from d in db.Accounts
where d.AccountName == accountName
select d).Single();
db.Accounts.Remove(t);
db.SaveChanges();
}