EF Code First : Add foreign key relationship

In the first article, I show how to create a database with one table using Code First. You can read it here : EF Code First : Simple sample

Now, we want to add a new table to work with foreign key. Let’s add a new Project class like this :

public class Project
{
    public int ProjectId { get; set; }
    public string Name { get; set; }
    public int ManagerId { get; set; }
    public Person Manager { get; set; }
}

You can see the Manager property is of type Person and I add ManagerId property to be the key between the two tables.

Now add the DbSet of Project as you’ve done for Person :

public DbSet Projects { get; set; }

And run the application.
Read more…

Jan 23rd, 2012 | Filed under EF

Series of articles about EF Code First

As I begin to work a lot with Entity Framework Code First, I decide to write some articles to share some samples that could be useful for beginners.
Here is how I think to organize it :

1 – First sample : A very simple example on how to create a database with a table
2 – Add foreign key relationship : We will enhanced the application created on the first tutorial to add relationships.
3 – Data Annotation and Code Fluent configuration
4 – Initialize database with data
5 – Table per Type and Table per Hierarchy

I hope I’ll find enough time to write all of this.
Hopefully, I already write the first one !

EF Code First : Simple sample

You heard about Entity Framework and want to try it. Let’s start with a very simple example. We will create a Console Application, add a class Person and generate the database from this class.
Open Visual Studio and create a Console Application. I called mine EFFirstSample.
Now, you have to allow Code First on your project. To do that, add Entity Framework from NuGet package. Open Visual Studio, go to Tools -> Library Package Manager -> Manage NuGet Packages and select EntityFrameworkpackage. It will add all references to your project.

Add package

Add package

Once added, check references in your project. EntityFramework should have appeared. You should also see a new file package.config. This file contains all information about NuGet packages installed.
Read more…

Jan 17th, 2012 | Filed under .Net 4.0, EF

[EF Code First] What happen to my Person table ?

I’m writing an article about EF Code Fisrt and i get a strange behaviour. I create a simple class Person :

public class Person
{
    public int PersonId { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public DateTime BirthDate { get; set; }
}

I create my context with a DbSet of Person :

public class MyContext : DbContext
{
   public DbSet<Person> Persons { get; set; }

    public MyContext()
    {}
}

Nothing special. I create a new Person in a console application and add it to the context, so the table Person is created and the new row added :

static void Main(string[] args)
{
    var person = new Person {FirstName = "Nadege", LastName = "Deroussen", BirthDate = DateTime.Now};
    using (var context = new MyContext())
    {
        context.Persons.Add(person);
    }
    Console.Write("Person saved !");
    Console.ReadLine();
}

I run the application and connect to my SqlExpress to check the database was created and this is what I obtain :

Screen capture of server explorer showing a table People

Where is the Person table ?

I get a People table. I return to Visual Studio to check I don’t make a mistake and I run a search on the entire solution. No occurence of “People”.
Where is my Person table ? Why do I get a People table ?
For information, I use Entity Framework 4.2.

Does somebody know how to explain that ?

Edit 19/01/2012 :
Ok, I get the answer from Diego Vega. It’s just because of pluralization rules. As my DbSet is named Persons, Code First, creating the table, singularize the name and Person become People and no Person as I was expecting.

Jan 17th, 2012 | Filed under .Net 4.0, EF

Entity Framework Code First by Julie Lerman and Rowan Miller

If you are looking for a great book to learn more about EF Code First, how it works and how to tune it, here is a really good book : Entity Framework Code First by Julie Lerman and Rowan Miller
I just finished it and I learned lots of things about configuring inheritance, mapping, caching and so much…

EF Code First, book cover

Entity Framework : Code First

You can find the book as paperback or Kindle edition.

Dec 6th, 2011 | Filed under EF

SPMetal and Publishing Field in Sharepoint

For a reason I don’t know, when you try to generate entity classes for your sharepoint site, SPMetal doesn’t generate property for Publishing field.

Imagine a field declare like that :

<Field ID="{B126F0CB-C1C3-476E-A499-80528707A784}" Name="Comments" DisplayName="Comments" Type="HTML" RichText="TRUE" RichTextMode="FullHtml" Required="TRUE" />

Here is a solution to this problem. Create a partial class for accessing your list and add manually a property like this :

public partial class MyClassCT
    {
        private string _comments;

        [Microsoft.SharePoint.Linq.ColumnAttribute(Name = "Comments", Storage = "_comments", FieldType = "Text")]
        public string Comments
        {
            get { return _comments; }
            set
            {
                if ((value != this._comments))
                {
                    this.OnPropertyChanging("Comments", this._comments);
                    this._comments= value;
                    this.OnPropertyChanged("Comments");
                }
            }
        }
    }

As you can see, I declare the fieldtype as Text and so, the property can be a simple string.
That’s it, you can now access the property like any others.

This works very well for reading, but when you try to create or update the list, you would get this error :
Incompatible column types. Previous type: Text . Current type: Invalid.

After some research, I can’t find which type should be use. I try FieldType = “Invalid” and …, it works.
Here is the column attribute definition :

[ColumnAttribute(Name = "Comments", Storage = "_comments", FieldType = "Invalid")]

There is some things I don’t understand. If someone can explain me why Invalid is considered as a good value, I would be very grateful !

NB : your field must be declare as HTML is the schema.xml.

Oct 4th, 2011 | Filed under Sharepoint, SP2010

DropDownList from enum in Asp.Net MVC

I found an excellent article that explain how to play with enum in a form. Stuart Leeks explains how to create an extension method to render enumeration as dropdownlist.
I’m not going to re-explain all. Just share the article with you : ASP.NET MVC – Creating a DropDownList helper for enums

Edit (20/09/2011) :
If you are interested by the PascalCaseWordSplittingEnumConverter, you can find the code in the comments.

Sep 19th, 2011 | Filed under ASP.Net MVC

Asp.Net MVC, Login and ReturnUrl

If you use AuthorizeAttribute in your controller, you surely encountered this kind of “issue”. Imagine, you try to create a blog application and on your Home, you let a “Add new article” link. As you want to protect your blog, you add an Authorize attribute on your Create method in the controller like this :

[Authorize(Roles = "Contributor, Administrator")]
public ActionResult Create()
{
    return View("Create");
}

Only Contributors could add articles to your blog. Fine !
Now, run your app and click on the “Add new article” link. Wow, you’re redirected to the login page. It’s perfect. You don’t have to manage it yourself. So, let’s try if it works. Connect with an account with Contributor rights. You are redirected to the Home page. Not so bad, but now, you have to click again on the link. It could be better if you can be redirected to the page you want to go.

It’s possible. You can modify your ActionLink to specify a returnUrl. It’s a simple attribute to add, like you can specify an area or a CSS style. Here is how to do :

@Html.ActionLink("Add new article", "Create", "Article", new { returnUrl = HttpContext.Current.Request.RawUrl }, null)

Now, when you click on the “Create” link and log in after being redirected, you are no longer redirected to the Home but to the Create page for articles.

Enjoy.

Sep 19th, 2011 | Filed under ASP.Net MVC

[EF] The specified type member ‘Property’ is not supported in LINQ to Entities

I’m playing with ASP.Net MVC and Entity Framework and I just encountered this error : “The specified type member ‘Property’ is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.“.
I’m trying to display a list of posts in my view (yes, it is MVC) and my post object has an enum property. It seems to be the problem.

Here is my object definition :

public enum PostStatut
    {
        Draft,
        Pending,
        Published,
        Deleted
    }

public class Article
    {
        public int ArticleID { get; set; }

        [Required(ErrorMessage = "Title is required")]
        public string Title { get; set; }

        [Required(ErrorMessage = "Content is required")]
        [AllowHtml]
        public string Content { get; set; }

        [Required(ErrorMessage = "DateCreation is mandatory")]
        [DisplayFormat(ApplyFormatInEditMode = false, DataFormatString = "{0:dd/MM/yyyy hh:mm}")]
        public DateTime DateCreation { get; set; }

        public virtual IList<Commentaire> Commentaires { get; set; }

        public int? AuthorID { get; set; }
        [ForeignKey("AuthorID")]
        public Person Author { get; set; }

        [Column("Statut", TypeName = "int")]
        public int InternalStatut { get; set; }

        [NotMapped]
        public PostStatut Statut
        {
            get { return (PostStatut)InternalStatut; }
            set { InternalStatut = (int)value; }
        }

You can see that I have an enum property : PostStatus and a property to manage enum with Entity Framework : InternalStatut, a simple integer.

In my home page, I try to display all my posts that have a Published status. here is my query :

return _context.Articles.Include("Commentaires").Include("Author").Where(a => a.Statut == PostStatut.Published).OrderBy(a => a.DateCreation);

You can see that I use the enumeration in the query and it seems to be THE problem. I modify my query to use the InternalStatut like this :

return _context.Articles.Include("Commentaires").Include("Author").Where(a => a.InternalStatut == (int)PostStatut.Published).OrderBy(a => a.DateCreation);

And now it works ! EF doesn’t support query with enumerations yet.

Sep 14th, 2011 | Filed under .Net, EF

[CSS] Display block doesn’t work with IE9

Yesterday, I try to make a simple drop down menu with CSS only.

I use a simple list like that :

<body>
	<ul class="navigation">
		<li>
			<a href="#">Menu 1</a>
		</li>
		<li>
			<a href="#">Menu 2</a>
		</li>
		<li>
			<a href="#">Menu 3</a>
		</li>
		<li>
			<a href="#">Settings</a>
			<div id="sub">
				<ul>
					<li>
						<a href="#">Display</a>
					</li>
					<li>
						<a href="#">Themes</a>
					</li>
					<li>
						<a href="#">Account</a>
					</li>
				</ul>
			</div>
		</li>
	</ul>
</body>

and add this simple css to hide or show my sub menu :

<style>
#sub ul {
    display: none;
}
li:hover > #sub ul {
    display: block;
}
</style>

I try to display this in Chrome and it works pretty fine. I open it with Firefox and my menu shows well too. I try to open it with IE 9 and here, nothing happen.
When my mouse is over the Settings item, nothing happens. My menu doesn’t show ? Is it a problem with display:block and IE 9 or is it my css that should be done another way ?
If somebody know how to do it works, just tell me ! I would be very happy.

I also try “inline” and “list-item” as value for the display attribute but I have the same result : works with Firefox and Chrome but not with IE 9 (I don’t try to use it with older version of IE 9).

Update :
Thanks to BatisteRouelle, I have my menu works with css only on IE 9.
I have to add a meta asking to render for IE 9 compatibility :

<meta http-equiv="X-UA-Compatible" content="IE=9" >

Update 12/08/2011: Trying to understand why this happen, we try to add the html page in an IIS Web Site and, using the default DOCTYPE, it works ! The problem is about autorization. IE, and only IE, don’t allow you to execute some code in local. It’s a security question. A little disturbing first but a good idea in fact.

Aug 11th, 2011 | Filed under General
Tags: ,

Switch to our mobile site