从 AddOrUpdate 中检索 id
本文关键字:id 检索 AddOrUpdate | 更新日期: 2023-09-27 18:35:36
我有一个实体如下:
public class PaletteColor
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ColorId { get; set; }
[MaxLength(10)]
[Index("ColorCodeIndex", IsUnique = true)]
public string ColorCode { get; set; }
public int ColorInt { get; set; }
}
我正在尝试编写一个方法,该方法将AddOrUpdate
一个实体并从保存的对象返回ColorId
。
public int AddOrUpdateColor(string ColorCode, int ColorInt)
{
db.ColorPalletteColors.AddOrUpdate(
c => c.ColorCode,
new ColorPaletteColor
{
ColorCode = ColorCode,
ColorInt = ColorInt
});
db.SaveChanges();
return c.; //Shall return the ColorId here.
}
我不太确定这种方法,我想从保存的对象返回一个 id,但无法指向它。
首先将对象分配给变量:
public int AddOrUpdateColor(string ColorCode, int ColorInt)
{
var color = new ColorPaletteColor
{
ColorCode = ColorCode,
ColorInt = ColorInt
};
db.ColorPalletteColors.AddOrUpdate(c => c.ColorCode, color);
db.SaveChanges();
return color.ColorId;
}
如果您首先将其分配给变量,Id
将自动填充:
public int AddOrUpdateColor(string ColorCode, int ColorInt)
{
var colorPaletteColor = new ColorPaletteColor
{
ColorCode = ColorCode,
ColorInt = ColorInt
};
db.ColorPalletteColors.AddOrUpdate(c => c.ColorCode, colorPaletteColor);
db.SaveChanges();
return colorPaletteColor.ColorId;
}
public int AddOrUpdateColor(string ColorCode, int ColorInt)
{
var color = db.ColorPalletteColors.FirstOrDefault(c => c.ColorCode == ColorCode);
if (color == null)
{
color = new ColorPaletteColor()
{
ColorCode = ColorCode;
};
db.ColorPaletteColors.AddObject(color);
}
color.ColorInt = ColorInt;
db.SaveChanges();
return color.ColorId; //Shall return the ColorId here.
}
我会说c.ColorId
应该用生成的ID填充,这样您就可以直接返回它。
在方法中使用var
来执行此操作...