为什么可以';我不能用方法添加吗

本文关键字:不能 方法 添加 为什么 | 更新日期: 2023-09-27 17:58:28

我的单位类别:

[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();
}

对于获取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。。。

我使用实体框架。

现在我该怎么办?

为什么可以';我不能用方法添加吗

您需要将公司状态标记为未更改,请尝试以下操作:

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
    };

我想对你有帮助:

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();
            }