I have a class that looks like this:
[Table("Coupons")]
public class Coupon
{
[Column("VET_ID")]
public string VetId { get; set; }
[Key]
public int CouponId { get; set; }
public string Name { get; set; }
public string ImageName { get; set; }
public string Text { get; set; }
[Column("ImageAlignment")]
public ImgAlignment Alignment { get; set; }
public enum ImgAlignment { TopLeft = 0, TopRight = 1, BottomLeft = 2, BottomRight = 3 };
/* public ImgAlignment Alignment
{
get { return (ImgAlignment) ImageAlignment; }
set
{ ImageAlignment = (int) value; }
}
*/
public string Html { get; set; }
}
The commented out bit is where I tried to use an enum property that mapped to an int in the DB, without expecting it to automagically work. Trouble is, this code:
Coupon newCoupon = new Coupon
{
Text = coupon,
Name = couponName,
VetId = data.VetId,
ImageName = string.Empty,
Alignment = Coupon.ImgAlignment.TopRight,
Html = string.Empty
};
db.Coupons.Add(newCoupon);
db.SaveChanges();
always throws an exception that the column 'ImageAlignment' cannot be null. But the object I am passing in, has a value for this property, I am setting it, the Alignment property should map to that column, right ?
2 Answers 2
cast to int to save
Alignment = (int)Coupon.ImgAlignment.TopRight
EFv4 doesn't support enums. You cannot use them for persistence. You must use int
mapped property instead and non mapped property converting it to enum as you showed in your example.
If you use enum property directly my expectation is that it is not mapped so setting it to enum value will not pass the value to database. In your database (I expect you are using existing one which is not generated by EF) your ImageAlignment
column is probably required and because your property is not mapped (enum property is skipped) it will not pass any value to it = exception.
-
OK, that would make sense to me, except I was mapping it to an int column which had a value, and then mapping that to an enum in code, and it still did not work. So, is there anything special I need to do to map to an int column ?cgraus– cgraus2011年12月07日 23:29:37 +00:00Commented Dec 7, 2011 at 23:29