EF 5 ENUM with Navigation - enums

I'm trying to use Enum support with EF 5 and dot.NET 4.5.
The situation I have is the following.
POCO:
public partial class tbl_pp_Message
{
public tbl_pp_Message()
{
this.tbl_pp_MessageDistribution = new List<tbl_pp_MessageDistribution>();
}
public int MessageId { get; set; }
public string Subject { get; set; }
public string From { get; set; }
public string Body { get; set; }
public int PriorityId { get; set; }
public System.DateTime CreateDate { get; set; }
public int CreateById { get; set; }
[ForeignKey("PriorityId")]
public virtual tbl_pp_MessagePriority tbl_pp_MessagePriority { get; set; }
public virtual ICollection<tbl_pp_MessageDistribution> tbl_pp_MessageDistribution { get; set; }
}
public partial class tbl_pp_MessagePriority
{
public tbl_pp_MessagePriority()
{
this.tbl_pp_Message = new List<tbl_pp_Message>();
}
public int MessagePriorityId { get; set; }
public string Description { get; set; }
public Nullable<int> DisplayOrder { get; set; }
public bool ShowAlert { get; set; }
public virtual ICollection<tbl_pp_Message> tbl_pp_Message { get; set; }
}
With the code listed above NOT using an ENUM the world is happy.
When I try to add an Enum the POCO will look like this.
[Flags]
public enum MessagePriorityEnum : int
{
NONE = 0,
Urgent = 1,
Normal = 2,
Low = 3
}
public partial class tbl_pp_Message
{
public tbl_pp_Message()
{
this.tbl_pp_MessageDistribution = new List<tbl_pp_MessageDistribution>();
}
public int MessageId { get; set; }
public string Subject { get; set; }
public string From { get; set; }
public string Body { get; set; }
public MessagePriorityEnum PriorityId { get; set; }
public System.DateTime CreateDate { get; set; }
public int CreateById { get; set; }
[ForeignKey("PriorityId")]
public virtual tbl_pp_MessagePriority tbl_pp_MessagePriority { get; set; }
public virtual ICollection<tbl_pp_MessageDistribution> tbl_pp_MessageDistribution { get; set; }
}
This will not work during a save because it doesn't like the ForeignKey attribute. This error will be thrown during a save.
Schema specified is not valid. Errors:
(129,6) : error 0112: The types of all properties in the Dependent Role of a referential constraint must be the same as the corresponding property types in the Principal Role. The type of property 'PriorityId' on entity 'tbl_pp_Message' does not match the type of property 'MessagePriorityId' on entity 'tbl_pp_MessagePriority' in the referential constraint 'tbl_pp_MessagePriority_tbl_pp_Message'.
If the navigation for tbl_pp_MessagePriority is removed from tbl_pp_Message POCO. And the navigation removed from tbl_pp_MessagePriority POCO back to tbl_pp_Message then it works.
With out the navigation removed it will generate a SQL statement like this.
insert [dbo].[tbl_pp_Message]
([Subject],
[From],
[Body],
[PriorityId],
[CreateDate],
[CreateById],
[tbl_pp_MessagePriority_MessagePriorityId])
values ('Test ENUM EF Code First 5.0' /* #0 */,
'Daniel.Bivens' /* #1 */,
'Test 01 Enum Body - The Magic Unicorn Edition' /* #2 */,
2 /* #3 */,
'2013-05-23T10:52:09' /* #4 */,
5 /* #5 */,
null)
select [MessageId]
from [dbo].[tbl_pp_Message]
where ##ROWCOUNT > 0
and [MessageId] = scope_identity()
It would be ok if the tbl_pp_MessagePriority_MessagePriorityId was not added to the insert.
What can be done to keep the navigaion in EF code first while using ENUM support? Is there a DataAnnotation or a Mapping API?
Please post any suggestions you may have. This project is not using an EDMX/T4 template.
Working POCO:
public partial class tbl_pp_Message
{
//public tbl_pp_Message()
//{
// this.tbl_pp_MessageDistribution = new List<tbl_pp_MessageDistribution>();
//}
public int MessageId { get; set; }
public string Subject { get; set; }
public string From { get; set; }
public string Body { get; set; }
public MessagePriorityEnum PriorityId { get; set; }
public System.DateTime CreateDate { get; set; }
public int CreateById { get; set; }
//[ForeignKey("PriorityId")]
//public virtual tbl_pp_MessagePriority tbl_pp_MessagePriority { get; set; }
//public virtual ICollection<tbl_pp_MessageDistribution> tbl_pp_MessageDistribution { get; set; }
}
public partial class tbl_pp_MessagePriority
{
//public tbl_pp_MessagePriority()
//{
// this.tbl_pp_Message = new List<tbl_pp_Message>();
//}
public int MessagePriorityId { get; set; }
public string Description { get; set; }
public Nullable<int> DisplayOrder { get; set; }
public bool ShowAlert { get; set; }
//public virtual ICollection<tbl_pp_Message> tbl_pp_Message { get; set; }
}
The working POCO would be ok if no navigation was needed.

The thing I was missing was setting the look-up table primary key to the same ENUM type instead of an int.
Working POCO with ENUM and navigation.
public partial class tbl_pp_Message
{
public tbl_pp_Message()
{
this.tbl_pp_MessageAction = new List<tbl_pp_MessageAction>();
this.tbl_pp_MessageAttachment = new List<tbl_pp_MessageAttachment>();
this.tbl_pp_MessageDistribution = new List<tbl_pp_MessageDistribution>();
}
public int MessageId { get; set; }
public string Subject { get; set; }
public string From { get; set; }
public string Body { get; set; }
public MessageTypeEnum TypeId { get; set; }
public System.DateTime CreateDate { get; set; }
public int CreateById { get; set; }
[ForeignKey("TypeId")]
public virtual tbl_pp_MessageType tbl_pp_MessageType { get; set; }
public virtual ICollection<tbl_pp_MessageAction> tbl_pp_MessageAction { get; set; }
public virtual ICollection<tbl_pp_MessageAttachment> tbl_pp_MessageAttachment { get; set; }
public virtual ICollection<tbl_pp_MessageDistribution> tbl_pp_MessageDistribution { get; set; }
}
public partial class tbl_pp_MessageType
{
public tbl_pp_MessageType()
{
this.tbl_pp_Message = new List<tbl_pp_Message>();
}
[Key]
public MessageTypeEnum MessageTypeId { get; set; }
public string Description { get; set; }
public Nullable<int> DisplayOrder { get; set; }
public bool ShowAlert { get; set; }
public virtual ICollection<tbl_pp_Message> tbl_pp_Message { get; set; }
}

Related

Web API JSON deserialization converting value issue

I am trying to insert JSON data into my models via EF 6. I am getting this error;
Inner Exception is {0}System.ArgumentException: Could not cast or convert from System.String to EPINMiddleWareAPI.Models.Serial.
konum: Newtonsoft.Json.Utilities.ConvertUtils.EnsureTypeAssignable(Object value, Type initialType, Type targetType)
konum: Newtonsoft.Json.Utilities.ConvertUtils.ConvertOrCast(Object initialValue, CultureInfo culture, Type targetType)
konum: Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(JsonReader reader, Object value, CultureInfo culture, JsonContract contract, Type targetType)
Message ---
{0}Error converting value "c57a55b5-b2d4-46e7-86e0-cc13726ca8a7" to type 'EPINMiddleWareAPI.Models.Serial'. Path 'coupons[0].serials[0]', line 1, position 310.
Here is my model structure:
public class ConfirmResponse
{
public int Id { get; set; }
public string referenceId { get; set; }
public string version { get; set; }
public string signature { get; set; }
public string paymentID { get; set; }
public string productCode { get; set; }
public string currency { get; set; }
public string ApplicationCode { get; set; }
public double unitPrice { get; set; }
public double totalPrice { get; set; }
public string purchaseStatusCode { get; set; }
public DateTime? purchaseStatusDate { get; set; }
public DateTime? requestDateTime { get; set; } = DateTime.Now;
public string merchantProductCode { get; set; }
public List<Coupon> coupons { get; set; }
}
public class Coupon
{
public int Id { get; set; }
public int ConfirmResponseID { get; set; }
public List<Serial> serials { get; set; }
public List<Pin> pins { get; set; }
public virtual ConfirmResponse confirmResponse { get; set; }
}
public class Serial
{
public int Id { get; set; }
public string serials { get; set; }
public int CouponID { get; set; }
public virtual Coupon coupons { get; set; }
}
My sample JSON:
"{\"referenceId\":\"0000000046\",\"paymentId\":\"MDO1037624\",\"productCode\":\"001002461285\",\"quantity\":\"1\",\"currency\":\"TL\",\"unitPrice\":\"46,47\",\"totalPrice\":\"46,47\",\"merchantProductCode\":\"\",\"purchaseStatusCode\":\"00\",\"purchaseStatusDate\":\"2019-03-17T20:58:48Z\",\"coupons\":[{\"serials\":[\"c57a55b5-b2d4-46e7-86e0-cc13726ca8a7\"],\"pins\":[\"T6VC-XC6X-3H6JS-NVWL-93PCa\"]}],\"version\":\"V1\",\"signature\":\"2f961c7dbc32c3bc128b6e69d19e8e1a\",\"applicationCode\":\"52e7cf966b724749a7c4efadc3727ed7\"}"
How can I fix this problem? I would like to insert this JSON into my database tables. I am using EF 6.
edit:
This model structure solved my problem. Now I can insert serials and pins into database.
public class ConfirmResponse
{
public int Id { get; set; }
public string referenceId { get; set; }
public string version { get; set; }
public string signature { get; set; }
public string paymentID { get; set; }
public string productCode { get; set; }
public string currency { get; set; }
public string ApplicationCode { get; set; }
public double unitPrice { get; set; }
public double totalPrice { get; set; }
public string purchaseStatusCode { get; set; }
public DateTime? purchaseStatusDate { get; set; }
public DateTime? requestDateTime { get; set; } = DateTime.Now;
public string merchantProductCode { get; set; }
public List<Coupon> coupons { get; set; }
}
public class Coupon
{
public int Id { get; set; }
public int ConfirmResponseID { get; set; }
public List<string> serials { get; set; }
public List<string> pins { get; set; }
public virtual ConfirmResponse confirmResponse { get; set; }
public List<string> StringsSerial
{
get { return serials; }
set { serials = value; }
}
public List<string> StringsPin
{
get { return pins; }
set { pins = value; }
}
[Required]
public string Serial
{
get { return String.Join(",", serials); }
set { serials = value.Split(',').ToList(); }
}
[Required]
public string Pin
{
get { return String.Join(",", pins); }
set { pins = value.Split(',').ToList(); }
}
}
Thanks in advance.
you're json is wrong
take a look into the coupons array, you initialize the serials array with an string/guid and not with a model of serial
it should be
"coupons": [{
{
"serials": [{
"serials": "c57a55b5-b2d4-46e7-86e0-cc13726ca8a7"
}
],
}
}
]...
I guess for Pins the same

Why is Entity Framework navigation property null?

I am use code first model with a relationship below
public class ApplicationUser : IdentityUser
{
public string UserFirstName { get; set; }
public string UserLastName { get; set; }
public string UserSchool { get; set; }
public UserProfileData UserProfileData { get; set; }
public int? MedicalSpecialtyId { get; set; }
public virtual MedicalSpecialty MedicalSpecialty { get; set; }
// public int? AnalyticsDataId { get; set; }
// public ICollection<AnalyticsData> AnalyticsDatas { get; set; }
}
public class MedicalSpecialty
{
public int Id { get; set; }
public string Description { get; set; }
// public int ApplicationUserId { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
public ICollection<ProgramDetailData> ProgramDetailDatas { get; set; }
}
And when I try to get a User's associated MedicalSpecialty object it is NULL
userSpecialtyName = currentUser.MedicalSpecialty.Description;
BUT when I run this code above it the currentUser.MedicalSpecialty is no longer NULL. What happened?? Somehow that LINQ query woke up the object and filled it with data
var userSpecialtyId = currentUser.MedicalSpecialtyId;
userSpecialtyName = _medicalSpecialtyRepository.Find
(x => x.Id == userSpecialtyId).FirstOrDefault().Description;
userSpecialtyName = currentUser.MedicalSpecialty.Description;

RestSharp - WP7 - Cannot deserialize XML to a list

I use RestSharp in my Windows Phone 7.1 project.
I have a response in XML format here:
https://skydrive.live.com/redir.aspx?cid=0b39f4fbbb0489dd&resid=B39F4FBBB0489DD!139&parid=B39F4FBBB0489DD!103&authkey=!AOdT-FiS6Mw8v5Y
I tried to deserialize that response to a class:
public class fullWall
{
public _user user { get; set; }
public int numberOfFriend { get; set; }
public int numberOfPhoto { get; set; }
public List<timhotPhotos> timhotPhotos { get; set; }
public fullWall()
{
timhotPhotos = new List<timhotPhotos>();
}
}
All properties are ok except the timhotPhotos list, as you can see here:
timhotPhotos class:
public class timhotPhotos
{
public string id { get; set; }
public string title { get; set; }
public string description { get; set; }
public string url { get; set; }
public double width { get; set; }
public double height { get; set; }
public DateTime createdDate { get; set; }
public _user user { get; set; }
public int numOfComment { get; set; }
public int numOfRate { get; set; }
public int numOfView { get; set; }
public bool rated { get; set; }
}
Where am I wrong?
You'll have to change the default XML deserializer to the DotNetXmlDeserializer, like this:
RestClient client;
client.AddHandler("application/xml", new DotNetXmlDeserializer());
Then, add the XmlElement attribute to the List<timhotPhotos> timhotPhotos property like this:
public class fullWall
{
public _user user { get; set; }
public int numberOfFriend { get; set; }
public int numberOfPhoto { get; set; }
[System.Xml.Serialization.XmlElement()]
public List<timhotPhotos> timhotPhotos { get; set; }
public fullWall()
{
timhotPhotos = new List<timhotPhotos>();
}
}
Now it should work fine!

Relationships between tables mvc3

I'm building website in MVC 3.
i am using EF code first in existing database.
my ET inside the model look like that:
public class Pages
{
[Required]
public int ID { get; set; }
public int ParentID { get; set; }
[Required]
public int PageType { get; set; }
[Required]
[DataType(DataType.Text)]
[DisplayName("כותרת")]
public string Title { get; set; }
public string SearchWords { get; set; }
public string Leng { get; set; }
public int? Sort { get; set; }
public string Modules { get; set; }
[ForeignKey("PageType")]
public virtual PagesType Type { get; set; }
public virtual IEnumerable<PagesType> Types { get; set; }
[ForeignKey("PageID")]
public ICollection<PageContent> PageContent { get; set; }
[ForeignKey("PageID")]
public virtual ICollection<ImagesTable> Images { get; set; }
}
public class PageContent
{
public int ID { get; set; }
public int PageID { get; set; }
public string Header { get; set; }
public string Text { get; set; }
[ForeignKey("ID")]
public virtual ICollection<Pages> Pages { get; set; }
}
as you see in my fist table that cold Pages i have a relationship to another table that named PageContent.
in my Pages class i had this code
[ForeignKey("PageID")]
public ICollection<PageContent> PageContent { get; set; }
now, when i trying to add new pageContent into new page i get an error.
see this code
public ActionResult AddPage(PageModel page)
{
SystemLogic cmd = new SystemLogic();
page.Leng = "he";
Models.Pages p = new Pages();
p.ParentID = page.ParentID;
PageContent pageContent = new PageContent();
pageContent.Text = page.Content;
p.PageContent.Add(pageContent);
The error is
Object reference not set to an instance of an object.
What i did wrong?
You will get the NRE at p.PageContent.Add(pageContent); because the collection is not initialized. Initialize the collections inside the constructor of Pages class.
public class Pages
{
public Pages()
{
PageContent = List<PageContent>();
Images = List<ImagesTable>();
}
[Required]
public int ID { get; set; }
public int ParentID { get; set; }
[Required]
public int PageType { get; set; }
[Required]
[DataType(DataType.Text)]
[DisplayName("כותרת")]
public string Title { get; set; }
public string SearchWords { get; set; }
public string Leng { get; set; }
public int? Sort { get; set; }
public string Modules { get; set; }
[ForeignKey("PageType")]
public virtual PagesType Type { get; set; }
public virtual IEnumerable<PagesType> Types { get; set; }
[ForeignKey("PageID")]
public ICollection<PageContent> PageContent { get; set; }
[ForeignKey("PageID")]
public virtual ICollection<ImagesTable> Images { get; set; }
}
Or before you add objects to the collection
if (p.PageContent == null) p.PageContent = new List<PageContent>();
p.PageContent.Add(pageContent);
You should consider using proper naming conventions(eg Page instead of Pages).

Entity Framework also Linq advice needed

i have got on my DB 3 tables
movies, workers, workermovies ( this is the Relationship table )
public class Movie
{
public Movie()
{
Genres = new List<Genre>();
Formats = new List<Format>();
ProductionCompanies = new List<ProductionCompany>();
Workers = new List<Worker>();
}
public int Id { get; set; }
public string Title { get; set; }
public DateTime ReleaseDate { get; set; }
public string StoryLine { get; set; }
public int RunTime { get; set; }
[ForeignKey("MPAARateId")]
public MPAARate MPAARate { get; set; }
public int MPAARateId { get; set; }
public byte[] ImageData { get; set; }
public string ImageMimeType { get; set; }
public DateTime CreatedDate { get; set; }
public string OfficialSite { get; set; }
public int Budget { get; set; }
public int StatusId { get; set; }
public virtual ICollection<Genre> Genres { get; set; }
public virtual ICollection<Format> Formats { get; set; }
public virtual ICollection<ProductionCompany> ProductionCompanies { get; set; }
public virtual ICollection<Worker> Workers { get; set; }
}
public class Worker
{
public int Id { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public DateTime Birthday { get; set; }
public string Biography { get; set; }
public string BornName { get; set; }
public double Height { get; set; }
public DateTime? Died { get; set; }
public byte[] ImageData { get; set; }
public string ImageMimeType { get; set; }
public bool IsActor { get; set; }
public bool IsDirector { get; set; }
public bool IsWriter { get; set; }
public bool IsProducer { get; set; }
public bool IsStar { get; set; }
public virtual ICollection<Movie> Movies { get; set; }
}
in this Relation i got the movieId and the workerId
but i also got some more fields if the person acted or writen or producer etc.
how do i define the relation entity class if needed
and when i want to get just the ppl that acted in the movie how do i wrote such a linq
query
You need to introduce an additional entity in your model WorkerMovie and convert the many-to-many relationship between Worker and Movie into two one-to-many relationships - one between Worker and WorkerMovie and the other between Movie and WorkerMovie. A sketch:
public class WorkerMovie
{
[Key, Column(Order = 0)]
public int WorkerId { get; set; }
[Key, Column(Order = 1)]
public int MovieId { get; set; }
public Worker Worker { get; set; }
public Movie Movie { get; set; }
public bool WorkedAsActor { get; set; }
public bool WorkedAsWriter { get; set; }
public bool WorkedAsProducer { get; set; }
// etc.
}
public class Movie
{
// ...
public virtual ICollection<WorkerMovie> WorkerMovies { get; set; }
// remove ICollection<Worker> Workers
}
public class Worker
{
// ...
public virtual ICollection<WorkerMovie> WorkerMovies { get; set; }
// remove ICollection<Movie> Movies
}
If you want only to find the workers who were actors in a particular movie with a movieId you can write:
var workersAsActors = context.WorkerMovies
.Where(wm => wm.MovieId == movieId && wm.WorkedAsActor)
.Select(wm => wm.Worker)
.ToList();
Here is another answer to a very similar question with many more examples of possible queries: Create code first, many to many, with additional fields in association table

Resources