无论如何,不确定问题的标题!我有我的模型类RandomStuff
,它具有Environment
虚拟属性。
public class RandomStuff
{
//NOT SHOWN ON FORM HIDDEN JUST TO MAKE IT EASIER IN DB
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Newtonsoft.Json.JsonProperty]
public int JobId { get; set; }
[Required]
[ForeignKey("Environment")]
[Newtonsoft.Json.JsonProperty]
[DataMember(IsRequired = true)]
public int EnvironmentId { get; set; }
[Newtonsoft.Json.JsonProperty ]
public virtual Environment Environment { get; set; }
}
我的环境如下:-
[Newtonsoft.Json.JsonObject(Newtonsoft.Json.MemberSerialization.OptIn)]
[DataContract]
public class Environment
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Newtonsoft.Json.JsonProperty]
public int Id { get; set; }
[Required]
[Newtonsoft.Json.JsonProperty]
[DataMember(IsRequired = true)]
public string Name { get; set; }
}
现在,在我的控制器中,我有:-
public HttpResponseMessage Save(RandomStuff stuff)
{
if (ModelState.IsValid)
{
//Some stuff here
db.RandomStuffs.Add(stuff);//When this excutes, it is
//inserting data in Environment table also.
db.SaveChanges();
}
}
现在,每当我在RandomStuff
表中添加东西时,它也在添加环境。
编辑:
我将尝试用我从ef-inserting-duplicate-parent-objects中获取的一般示例进行解释
public class Foo
{
public int FooId {get;set;}
public virtual ICollection<Bar> Bars {get;set;}
}
public class Bar
{
public int BarId {get;set;}
public strung BarName {get;set;}
}
现在,如果上面是我的模型结构。我正在尝试将一个 Foo 数据添加到我的数据库中。
db.Foo.Add(new Foo{
FooId=1,
Bars=new List<Bar>(){
new Bar{
BarId=2,
BarName="Something"
}
}
})//Something of this sort will be my data, which needs to be inserted
//Now this record "new Bar{BarId=2, BarName="Something"}" is already present in DB
现在,正在发生的事情是,它在 Foo 表中插入 id=1 的数据,并且还在 Bars 表中添加了 id 为 2 的重复数据。
此外,如果我使用类似下面的东西,我的要求得到满足:
db.Entry(fooModelDataComingFromSomewhere.Bars).State = EntityState.Unchanged;