0

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 ?

asked Dec 7, 2011 at 0:39

2 Answers 2

1

cast to int to save

Alignment = (int)Coupon.ImgAlignment.TopRight
answered Jun 19, 2012 at 13:23
0

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.

answered Dec 7, 2011 at 8:51
1
  • 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 ? Commented Dec 7, 2011 at 23:29

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.