我的单元课:
[Column("FldKeyId")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Required]
[Key]
public int MyKeyId { get; set; }
[Column("FldCode")]
[Required]
[Index(IsUnique = true)]
public int MyCode
{
get { return _Code; }
set { _Code = value; }
}
[Column ("FldName")]
[Required]
public string MyName { get; set; }
[Column("FldDescription")]
[Required]
public string MyDescription { get; set; }
[Column("FldModifiedUserId")]
[Required]
public int ModifiedUserId { get; set; }
[Column("FldModificationDate")]
[Required]
public DateTime ModificationDate { get; set; }
[Column("FldDeleteFlag")]
[Required]
public int DeleteFlag { get; set; }
public Company Company { get; set; }
我有Add
的方法:
public static void AddUnit(int Code,string Name,string Description,int ModifiedUserId,DateTime ModificationDate,Company CompanyId)
{
ContexManager contex = new ContexManager();
Unit Row = new Unit()
{
MyCode = Code,
MyName = Name,
MyDescription = Description,
ModifiedUserId = ModifiedUserId,
ModificationDate = ModificationDate,
Company=CompanyId,
DeleteFlag = 0
};
contex.units.Add(Row);
contex.SaveChanges();
}
对于get companyId,我有另一种方法:
public static Company GetCompany(int KeyId)
{
ContexManager contex=new ContexManager();
Company Row = new Company();
Row = contex.Companies.Where(c => c.MyKeyId == KeyId).Single();
return Row;
}
现在用于此:
Unit.AddUnit(10, "ab", "bch", 2, DateTime.Now, Company.GetCompany(6));
我有一条记录,即companyId为6,但问题是当我添加Unit
时添加了Company
...
我使用实体框架。
现在我该怎么做?
答案 0 :(得分:0)
我想帮助你:
using (ContexManager contex = new ContexManager())
{
var company = contex.Companies.Where(c => c.MyKeyId == companyId).Single();
Row = contex.Companies.Where(c => c.MyKeyId == KeyId).Single();
Unit Row = new Unit()
{
MyCode = Code,
MyName = Name,
MyDescription = Description,
ModifiedUserId = ModifiedUserId,
ModificationDate = ModificationDate,
Company = company,
DeleteFlag = 0
};
contex.units.Add(Row);
contex.SaveChanges();
}
答案 1 :(得分:0)
您需要将公司状态标记为未更改,请尝试以下操作:
ContexManager contex = new ContexManager();
// change Company CompanyId parameter to objCompany as it is not Id
context.Entry(objCompany).State = EntityState.Unchanged;
Unit Row = new Unit()
{
MyCode = Code,
MyName = Name,
MyDescription = Description,
ModifiedUserId = ModifiedUserId,
ModificationDate = ModificationDate,
Company=objCompany,
DeleteFlag = 0
};