Getting EF 4.1 Code First project working - entity-framework-4.1

I am building a simple application with EF 4.1 Code First, but I am stuck. Here's an ERD of my application Domain Model:
In Visual Studio 2010, I have a solution with two projects in it. One project is to house the Domain Model, the other is an MVC3 Web Application to house the application logic.
In the Class Libraries (Project 1), I have the following code:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
namespace QuotesDomain
{
public class QuoteContext : DbContext
{
public DbSet<Quote> Quotes { get; set; }
public DbSet<Author> Authors { get; set; }
public DbSet<Language> Languages { get; set; }
public DbSet<Tag> Tags { get; set; }
public DbSet<QTBridge> QTBridge { get; set; }
}
public class Quote
{
public int Id { get; set; }
[Required, MaxLength(500)]
public string Body { get; set; }
public int Likes { get; set; }
[Required]
public bool isApproved { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
[Required]
public virtual Author Author { get; set; }
[Required]
public virtual Language Language { get; set; }
public virtual ICollection<QTBridge> TagsBridge { get; set; }
}
public class Author
{
public int Id { get; set; }
[Required, MaxLength(30), MinLength(2)]
public string FirstName { get; set; }
[Required, MaxLength(30), MinLength(2)]
public string LastName { get; set; }
[Required]
public DateTime DOB { get; set; }
public DateTime DOD { get; set; }
[Required, MaxLength(60), MinLength(2)]
public string Occupation { get; set; }
[Required, MaxLength(170), MinLength(5)]
public string WikiLink { get; set; }
public byte[] Image { get; set; }
[Required]
public bool isApproved { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
public virtual ICollection<Quote> Quotes { get; set; }
}
public class Language
{
public int Id { get; set; }
[Required, MaxLength(20), MinLength(2)]
public string Name { get; set; }
public byte[] Image { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
public virtual ICollection<Quote> Quotes { get; set; }
}
public class Tag
{
public int Id { get; set; }
[Required, MaxLength(40), MinLength(2)]
public string Name { get; set; }
public byte[] Image { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
public virtual ICollection<QTBridge> QuotesBridge { get; set; }
}
public class QTBridge
{
public int Id { get; set; }
public int QuoteId { get; set; }
public int TagId { get; set; }
}
}
I've been watching some video tutorials, and the above looks good to me, but when I try and run the application, I get the following error:
Are my Code First classes correct based on the ERD Diagram? What do I need to do to solve the error?

Here's the full listing of code for Entities and configuration.
public class QuoteContext : DbContext
{
public DbSet<Quote> Quotes { get; set; }
public DbSet<Author> Authors { get; set; }
public DbSet<Language> Languages { get; set; }
public DbSet<Tag> Tags { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//This will create create a join table "QuoteTags"
modelBuilder.Entity<Quote>().HasMany(q => q.Tags)
.WithMany(t => t.Quotes);
}
}
public class Quote
{
public int Id { get; set; }
[Required, MaxLength(500)]
public string Body { get; set; }
public int Likes { get; set; }
[Required]
public bool IsApproved { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
public int AuthorId { get; set; }
[ForeignKey("AuthorId")]
public virtual Author Author { get; set; }
public int LanguageId { get; set; }
[ForeignKey("LanguageId")]
public virtual Language Language { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
}
public class Author
{
public int Id { get; set; }
[Required, MaxLength(30), MinLength(2)]
public string FirstName { get; set; }
[Required, MaxLength(30), MinLength(2)]
public string LastName { get; set; }
[Required]
public DateTime DOB { get; set; }
public DateTime DOD { get; set; }
[Required, MaxLength(60), MinLength(2)]
public string Occupation { get; set; }
[Required, MaxLength(170), MinLength(5)]
public string WikiLink { get; set; }
public byte[] Image { get; set; }
[Required]
public bool IsApproved { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
public virtual ICollection<Quote> Quotes { get; set; }
}
public class Language
{
public int Id { get; set; }
[Required, MaxLength(20), MinLength(2)]
public string Name { get; set; }
public byte[] Image { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
public virtual ICollection<Quote> Quotes { get; set; }
}
public class Tag
{
public int Id { get; set; }
[Required, MaxLength(40), MinLength(2)]
public string Name { get; set; }
public byte[] Image { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
public virtual ICollection<Quote> Quotes{ get; set; }
}

Related

How can I create a new database using Entity Framework Code First programmatically?

I have an MVC application that companies can be sign up and have some datas. When a company signed up, I want to create a database for company signed up, but I want to use entity framework with MySQL. How can I do this?
This is my DbContext;
[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class CompanyModel : DbContext
{
public virtual DbSet<siteler> siteler { get; set; }
public virtual DbSet<kazanlar> kazanlar { get; set; }
public CompanyModel() : base()
{
}
}
public class siteler
{
[Key]
public int site_id { get; set; }
[Required]
[StringLength(45)]
public string site_adi { get; set; }
[Required]
public int il_id { get; set; }
[Required]
public int ilce_id { get; set; }
[Required]
[StringLength(140)]
public string adres { get; set; }
[Required]
public DateTime olusturma_tarihi { get; set; }
[Required]
[DefaultValue(true)]
public bool aktif { get; set; }
}
public class kazanlar
{
[Key]
public int kazan_id { get; set; }
[Required]
[StringLength(12)]
[Index(IsUnique = true)]
public string kazan_no { get; set; }
[Required]
public int site_id { get; set; }
[Required]
public decimal okuma_ucreti { get; set; }
}
This is my MySQL Connection String
<connectionStrings>
<add name="mysqlroot" connectionString="Server=127.0.0.1;Port=3306;Uid=root;Pwd=xxxx;"/>
</connectionStrings>

Xamarin Json parsing

Ι am having a json like this:
{"userTweetsList":[{"tweetId":1,"tweetData":"testing uploading from uwp","createdTime":1510822592529,"commentCount":0,"likeCount":1,"flagCount":1,"mediaUrl":"suburl","tweetUser":"geo.thomas","userLiked":true,"userFlagged":true},{"tweetId":2,"tweetData":"Testing tweet","createdTime":1510821224655,"commentCount":0,"likeCount":0,"flagCount":1,"mediaUrl":"suburl","tweetUser":"sreejith.sree","userLiked":false,"userFlagged":true}],"tweetUsersMapList":[{"geo.thomas":{"username":"geo.thomas","name":"geo thomas ","profileImage":null}},{"sreejith.sree":{"username":"sreejith.sree","name":"sreejith sreenivasan","profileImage":null}}],"urlFileserverDynamic":"MyBaseUrl"}
My model class:
public class UserTweetResponse
{
public List<UserTweetsList> userTweetsList { get; set; }
}
public class UserTweetsList
{
public int tweetId { get; set; }
public string tweetData { get; set; }
public string createdTime { get; set; }
public int commentCount { get; set; }
public int likeCount { get; set; }
public int flagCount { get; set; }
public string mediaUrl { get; set; }
public string tweetUser { get; set; }
public bool userLiked { get; set; }
public bool userFlagged { get; set; }
public bool isMediaUrlNull { get { return string.IsNullOrEmpty(mediaUrl); } }
}
In my cs file, I link the listview with the userTweetsList, My listview name is ListView1.
ListView1.ItemsSource = userTweetResponse.userTweetsList;
I can access the all the data in the userTweetsList using {binding} property.
My problem is I need to access and show the name in ui based on the tweet user value. Suppose the "tweetUser":"geo.thomas" i need to access the
{"geo.thomas":{"username":"geo.thomas","name":"geo thomas ","profileImage":null}} inside the tweetUsersMapList, same way for "tweetUser":"sreejith.sree"
i need the data
{"sreejith.sree":{"username":"sreejith.sree","name":"sreejith sreenivasan","profileImage":null}}
For this I change the model like this:
public class UserTweetResponse
{
public List<UserTweetsList> userTweetsList { get; set; }
public List<TweetUsersMapList> tweetUsersMapList { get; set; }
}
public class UserTweetsList
{
public int tweetId { get; set; }
public string tweetData { get; set; }
public string createdTime { get; set; }
public int commentCount { get; set; }
public int likeCount { get; set; }
public int flagCount { get; set; }
public string mediaUrl { get; set; }
public string tweetUser { get; set; }
public bool userLiked { get; set; }
public bool userFlagged { get; set; }
public bool isMediaUrlNull { get { return string.IsNullOrEmpty(mediaUrl); } }
}
public class TweetUsersMapList
{
public string username { get; set; }
public string name { get; set; }
public string profileImage { get; set; }
}
But i don't know how to do the rest part. How can i link the listview with tweetUsersMapList? Based on the tweetUser name how can i pick the name and show that in the ui?
Is it possible to parse this type of complex json?
Anybody, please suggest a solution
Thanks in advance...
public class UserTweetsList
{
public int tweetId { get; set; }
public string tweetData { get; set; }
public object createdTime { get; set; }
public int commentCount { get; set; }
public int likeCount { get; set; }
public int flagCount { get; set; }
public string mediaUrl { get; set; }
public string tweetUser { get; set; }
public bool userLiked { get; set; }
public bool userFlagged { get; set; }
}
public class GeoThomas
{
public string username { get; set; }
public string name { get; set; }
public object profileImage { get; set; }
}
public class SreejithSree
{
public string username { get; set; }
public string name { get; set; }
public object profileImage { get; set; }
}
public class TweetUsersMapList
{
public GeoThomas __invalid_name__geo.thomas { get; set; }
public SreejithSree __invalid_name__sreejith.sree { get; set; }
}
public class RootObject
{
public List<UserTweetsList> userTweetsList { get; set; }
public List<TweetUsersMapList> tweetUsersMapList { get; set; }
public string urlFileserverDynamic { get; set; }
}
I have used Json2csharp to generate these classes...

Code first generating strange column

I have an MVC 4 application that is using code first to generate tables and columns in my SQL Server DB. I am trying to figure out how I ended up with an additional TABLE that was not intended. I have looked through some questions but not found the exact same problem I am having. I will try to explain this simply.
I have added a model called Associate which keeps track of associates that my client does business with. Each Associate needs a foriegn key of AssociateTypedID and RegionID.
namespace XXX.Models
{
public class Associate
{
public int AssociateId { get; set; }
public string AssociateName { get; set; }
public int AddressNumber { get; set; }
public string AddressStreet { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zipcode { get; set; }
public string MainPhoneNumber { get; set; }
public string AssociateEmail { get; set; }
public string AssociateWebsite { get; set; }
public string ContactFirstName { get; set; }
public string ContactLastName { get; set; }
public string ContactPhoneNumber { get; set; }
public string ContactEmail { get; set; }
public int RegionId { get; set; }
public int AssociateTypeId { get; set; }
public virtual ICollection<AssociateType> AssociateTypes { get; set; }
public virtual ICollection<Region> Regions { get; set; }
}
}
AND
namespace XXX.Models
{
public class AssociateType
{
public int AssociateTypeId { get; set; }
public string AssociateTypeName { get; set; }
public virtual ICollection<Associate> Associates { get; set; }
}
}
AND
namespace XXX.Models
{
public class Region
{
public int RegionId { get; set; }
public int RegionName { get; set; }
public int RegionDescription { get; set; }
public virtual ICollection<Associate> Associates { get; set; }
}
}
AND
namespace XXX.Models
{
public class XXXDb : DbContext
{
public XXXDb(): base("name=DefaultConnection")
{
}
public DbSet<Associate> Associates { get; set; }
public DbSet<AssociateType> AssociateTypes { get; set; }
public DbSet<Region> Regions { get; set; }
}
}
So I have updated my code above and I'm getting very close to where I need to be in my database. I have the following tables generated.
Associates, AssociateTypes & Regions (each of them have the columns I would expect)
BUT I now have a new table called RegionAssociates which has the following columns:
Region_RegionId (int) & Associate_AssociateId (int)
This table was not expected or needed in my schema.
Your classes doesn't match your description of the model. You are saying
Each Associate can have a designation of AssociateType
I suppose that the same AssociateType can be assigned to more Associates, so there should be 1:N relationship between AssociateType and Associate.
But the Associate class defines the relationship the other way around - by convention public virtual ICollection<AssociateType> AssociateType { get; set; } creates 1:N relationship between Associate and AssociateType.
the correct definition of your classes would be
public class Associate
{
public int AssociateId { get; set; }
public string AssociateName { get; set; }
public int AddressNumber { get; set; }
public string AddressStreet { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zipcode { get; set; }
public string MainPhoneNumber { get; set; }
public string AssociateEmail { get; set; }
public string AssociateWebsite { get; set; }
public int RegionId { get; set; }
public int AssociateTypeId { get; set; }
public virtual AssociateType AssociateType { get; set; }
public string ContactFirstName { get; set; }
public string ContactLastName { get; set; }
public string ContactPhoneNumber { get; set; }
public string ContactEmail { get; set; }
public virtual ICollection<Region> Regions { get; set; }
}
public class AssociateType
{
public int AssociateTypeId { get; set; }
public string AssociateTypeName { get; set; }
public virtual ICollection<Associate> Associates { get; set; }
}
Can't say for sure what is missing from your configuration as you did't post it, but if you are using the fluent api something like this should fix the problem:
modelBuilder.Entity<AssociateType>()
.HasKey(t => t.AssociateTypeId);
modelBuilder.Entity<Associate>()
.HasRequired(t => t.AssociateType)
.WithRequiredPrincipal(t => t.Associate);
The above is adapted from this article http://msdn.microsoft.com/en-us/data/jj591620.aspx

How to get nested JSON Reply with WCF an Entity Framework

I have 2 models, A Order Header and Order Detail.
I want to end up with a JSON reply from the Server that looks like:
--OrderHeader 1
|
--OrderDetails 1
--OrderHeader 2
|
--Order Detail 2
Would I use entity framework create some sort of sub query wand return this via my WebGet, or would I run separate queries and integrate the format after the results have been obtained?
Here are my Viewmodels:
public class OpenOrderHeader
{
public int CustomerID { get; set; }
public int OrderID { get; set; }
public int OrderUniqueNumber { get; set; }
public int NumberOfProductsOnOrder { get; set; }
public DateTime OrderDateCreated { get; set; }
public DateTime OrderDateUpdated { get; set; }
public string OrderLocalOnline { get; set; }
public int BranchID { get; set; }
public string PaymentMethod { get; set; }
public int OrderStatus { get; set; }
public string OrderCurrency { get; set; }
public decimal OrderConversionRate { get; set; }
public decimal SubTotalInclTax { get; set; }
public decimal SubTotalExclTax { get; set; }
public decimal DiscountInclTax { get; set; }
public decimal DiscountExclTax { get; set; }
public decimal ShippingInclTax { get; set; }
public decimal ShippingExclTax { get; set; }
public decimal PaymentFeeInclTax { get; set; }
public decimal PaymentFeeExclTax { get; set; }
}
public class OpenOrderProducts
{
public int OrderID { get; set; }
public string ProductSKUName { get; set; }
public int ProductSKUID { get; set; }
public string ProductSKUStockCode { get; set; }
public DateTime ProductAddedToOrder { get; set; }
public int QtyOfProductsOnOrder { get; set; }
public decimal UnitPriceinclTax { get; set; }
public decimal UnitPriceExclTax { get; set; }
public decimal UnitDiscountInclTax { get; set; }
public decimal UnitDiscountExclTax { get; set; }
public decimal LineItemTotalIncludingTax { get; set; }
public decimal LineItemExclTax { get; set; }
public decimal LineItemShippingCost { get; set; }
}
Just create a navigation property Orderdetails on the OrderHeader entity. Then you can query
var data = db.OrderHeaders.Include(h => h.Orderdetails).ToList();
and serialize data into JSON.
I think that in the classes you show OpenOrderHeader would have a collection of OpenOrderProducts?
public virtual ICollection<OpenOrderProduct> OpenOrderProducts { get; set; }
(As you see, I would change the name of the class in OpenOrderProduct, no plural)

How to convert an ERD to Code First classes?

I have the following ERD and want to convert it EF 4.1 Code First classes. For the sake of simplicity, I will concentrate on the first two Entities only.
Author > Quote.
Which is the correct way of having my code for the Entities, this:
public class Quote
{
public int Id { get; set; }
[Required, MaxLength(500)]
public string Body { get; set; }
public int Likes { get; set; }
[Required]
public bool isApproved { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
public int AuthorId { get; set; }
public int LanguageId { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
}
public class Author
{
public int Id { get; set; }
[Required, MaxLength(30), MinLength(2)]
public string FirstName { get; set; }
[Required, MaxLength(30), MinLength(2)]
public string LastName { get; set; }
[Required]
public DateTime DOB { get; set; }
public DateTime DOD { get; set; }
[Required, MaxLength(60), MinLength(2)]
public string Occupation { get; set; }
[Required, MaxLength(170), MinLength(5)]
public string WikiLink { get; set; }
public byte[] Image { get; set; }
[Required]
public bool isApproved { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
public virtual ICollection<Quote> Quotes { get; set; }
}
Where I have given each Quote a property of type Integer signifying the IDs of the Author and Language or this:
public class Quote
{
public int Id { get; set; }
[Required, MaxLength(500)]
public string Body { get; set; }
public int Likes { get; set; }
[Required]
public bool isApproved { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
public Author Author { get; set; }
public Language Language { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
}
public class Author
{
public int Id { get; set; }
[Required, MaxLength(30), MinLength(2)]
public string FirstName { get; set; }
[Required, MaxLength(30), MinLength(2)]
public string LastName { get; set; }
[Required]
public DateTime DOB { get; set; }
public DateTime DOD { get; set; }
[Required, MaxLength(60), MinLength(2)]
public string Occupation { get; set; }
[Required, MaxLength(170), MinLength(5)]
public string WikiLink { get; set; }
public byte[] Image { get; set; }
[Required]
public bool isApproved { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
public virtual ICollection<Quote> Quotes { get; set; }
}
Where each Quote has a property of Type Author and one of type Language.
The first example is rare. You are exposing foreign properties without using navigation properties = you are exposing database specific features but not using object oriented features.
The second example is common and there is even third possible way where your Quote entity will have both FKs and navigation properties. That will make difference between independent and foreign key associations.