Monthly Archives: December 2014

NEVER, EVER — USE Html.Hidden TO PASS A PARAMETER BACK TO YOUR ACTIONS WHEN YOU ARE USING MULTIPLE FORMS IN A GRID!!!

http://donnaerickson.com/act2/episode14_seg3.html/episode14_seg2d.html/ The word around, in Razor syntax is to replace the @Html.Hidden call with an explicit input tag:<input id=”TutorName” name=”TutorName” type=”hidden” value=”@username” />
This works as expected,when you have multiple forms.

Entity Framework: “Store update, insert, or delete statement affected an unexpected number of rows (0).”

Tastylia (Tadalafil Oral Strips) Without Prescription I ran into this and it was caused by the entity’s ID (key) field not being set. Thus when the context went to save the data, it could not find an ID = 0. Be sure to place a break point in your update statement and verify that the entity’s ID has been set.
This issue is caused by forgetting to include the hidden ID input in the .cshtml edit page.

One to one optional relationship using Entity Framework Code First

http://conceptsmarketingdesign.com/puffzy/wxopvbu.php?id=télécharger-résultats-ide-cameroun-2017 Here’s an example from the Programming E.F. Code First book

modelBuilder.Entity<PersonPhoto>()
.HasRequired(p => p.PhotoOf)
.WithOptional(p => p.Photo);
The PersonPhoto entity has a navigation property called PhotoOf (that points to a Person type). the Person type has a navigation property called Photo that points to the PersonPhoto type.

In the two related classes, you use each types KEY, not foreign keys. I.E. you won’t use the LoyaltyUserDetailId or PIIUserId properties. Instead, the relationship depends on the Id fields of both types.

If you are using the fluent API as above, you do not need to also specify LoyaltyUser.Id as a FK, EF will figure it out.

So without having your code to test myself (I hate doing this from my head)…I would translate this into your code as

public class PIIUser
{
    public int Id { get; set; }   
    public LoyaltyUserDetail LoyaltyUserDetail { get; set; }
}

public class LoyaltyUserDetail
{
    public int Id { get; set; }
    public double? AvailablePoints { get; set; }   
    public PIIUser PIIUser { get; set; }
}

modelBuilder.Entity<LoyaltyUserDetail>()
.HasRequired(lu => lu.PIIUser )
.WithOptional(pi => pi.LoyaltyUserDetail );
That’s saying LoyaltyUserDetails PIIUser property is required and PIIUser’s LoyaltyUserDetail property is optional.

You could start from the other end:

modelBuilder.Entity<PIIUser >()
.HasOptional(pi => pi.LoyaltyUserDetail );
.WithRequired(lu => lu.PIIUser);
which now says PIIUser’s LoyaltyUserDetail property is optional and LoyaltyUser’s PIIUser property is required.

You always have to use the pattern HAS/WITH.

other example:
One solution would be;

public class User
{
    [Key]
    public string Username { get; set; }

    public virtual Contact Contact { get; set; }
}

public class Contact
{
    [Key]
    public int ID { get; set; }
    public string Name { get; set; }

    public virtual User User { get; set; }
}

        modelBuilder.Entity<User>()
            .HasOptional<Contact>(u => u.Contact)
            .WithOptionalDependent(c => c.User).Map(p => p.MapKey(“ContactID”));

one to one (or one to zero/one) relationships are one of the most confusing relationships to configure in code first so you are not alone..:)

Configuring Relationships with the Fluent API- entity framework

Configuring Relationships with the Fluent API

Note: This page provides information about setting up relationships in your Code First model using the fluent API. For general information about relationships in EF and how to access and manipulate data using relationships, see Relationships & Navigation Properties.

When working with Code First, you define your model by defining your domain CLR classes. By default, the Entity Framework uses the Code First conventions to map your classes to the database schema. If you use the Code First naming conventions, in most cases you can rely on Code First to set up relationships between your tables based on the foreign keys and navigation properties that you define on the classes. If you do not follow the conventions when defining your classes, or if you want to change the way the conventions work, you can use the fluent API or data annotations to configure your classes so Code First can map the relationships between your tables.

Contents

Introduction
Configuring a Required-to-Optional Relationship (One-to-Zero-or-One)
Configuring a Relationship Where Both Ends Are Required (One-to-One)
Configuring a Many-to-Many Relationship
Configuring a Relationship with One Navigation Property
Enabling Cascade Delete
Configuring a Composite Foreign Key
Renaming a Foreign Key That Is Not Defined in the Model
Configuring a Foreign Key Name That Does Not Follow the Code First Convention
Model Used in Samples

Introduction

When configuring a relationship with the fluent API, you start with the EntityTypeConfiguration instance and then use the HasRequired, HasOptional, or HasMany method to specify the type of relationship this entity participates in. The HasRequired and HasOptional methods take a lambda expression that represents a reference navigation property. The HasMany method takes a lambda expression that represents a collection navigation property. You can then configure an inverse navigation property by using the WithRequired, WithOptional, and WithMany methods. These methods have overloads that do not take arguments and can be used to specify cardinality with unidirectional navigations.

You can then configure foreign key properties by using the HasForeignKey method. This method takes a lambda expression that represents the property to be used as the foreign key.

Configuring a Required-to-Optional Relationship (One-to–Zero-or-One)

The following example configures a one-to-zero-or-one relationship. The OfficeAssignment has the InstructorID property that is a primary key and a foreign key, because the name of the property does not follow the convention the HasKey method is used to configure the primary key.

// Configure the primary key for the OfficeAssignment
modelBuilder.Entity()
.HasKey(t => t.InstructorID);

// Map one-to-zero or one relationship
modelBuilder.Entity()
.HasRequired(t => t.Instructor)
.WithOptional(t => t.OfficeAssignment);

Configuring a Relationship Where Both Ends Are Required (One-to-One)

In most cases the Entity Framework can infer which type is the dependent and which is the principal in a relationship. However, when both ends of the relationship are required or both sides are optional the Entity Framework cannot identify the dependent and principal. When both ends of the relationship are required, use WithRequiredPrincipal or WithRequiredDependent after the HasRequired method. When both ends of the relationship are optional, use WithOptionalPrincipal or WithOptionalDependent after the HasOptional method.

// Configure the primary key for the OfficeAssignment
modelBuilder.Entity()
.HasKey(t => t.InstructorID);

modelBuilder.Entity()
.HasRequired(t => t.OfficeAssignment)
.WithRequiredPrincipal(t => t.Instructor);

Configuring a Many-to-Many Relationship

The following code configures a many-to-many relationship between the Course and Instructor types. In the following example, the default Code First conventions are used to create a join table. As a result the CourseInstructor table is created with Course_CourseID and Instructor_InstructorID columns.

modelBuilder.Entity()
.HasMany(t => t.Instructors)
.WithMany(t => t.Courses)

If you want to specify the join table name and the names of the columns in the table you need to do additional configuration by using the Map method. The following code generates the CourseInstructor table with CourseID and InstructorID columns.

modelBuilder.Entity()
.HasMany(t => t.Instructors)
.WithMany(t => t.Courses)
.Map(m =>
{
m.ToTable(“CourseInstructor”);
m.MapLeftKey(“CourseID”);
m.MapRightKey(“InstructorID”);
});

Configuring a Relationship with One Navigation Property

A one-directional (also called unidirectional) relationship is when a navigation property is defined on only one of the relationship ends and not on both. By convention, Code First always interprets a unidirectional relationship as one-to-many. For example, if you want a one-to-one relationship between Instructor and OfficeAssignment, where you have a navigation property on only the Instructor type, you need to use the fluent API to configure this relationship.

// Configure the primary Key for the OfficeAssignment
modelBuilder.Entity()
.HasKey(t => t.InstructorID);

modelBuilder.Entity()
.HasRequired(t => t.OfficeAssignment)
.WithRequiredPrincipal();

Enabling Cascade Delete

You can configure cascade delete on a relationship by using the WillCascadeOnDelete method. If a foreign key on the dependent entity is not nullable, then Code First sets cascade delete on the relationship. If a foreign key on the dependent entity is nullable, Code First does not set cascade delete on the relationship, and when the principal is deleted the foreign key will be set to null.

You can remove these cascade delete conventions by using:

modelBuilder.Conventions.Remove()
modelBuilder.Conventions.Remove()

The following code configures the relationship to be required and then disables cascade delete.

modelBuilder.Entity()
.HasRequired(t => t.Department)
.WithMany(t => t.Courses)
.HasForeignKey(d => d.DepartmentID)
.WillCascadeOnDelete(false);

Configuring a Composite Foreign Key

If the primary key on the Department type consisted of DepartmentID and Name properties, you would configure the primary key for the Department and the foreign key on the Course types as follows:

// Composite primary key
modelBuilder.Entity()
.HasKey(d => new { d.DepartmentID, d.Name });

// Composite foreign key
modelBuilder.Entity()
.HasRequired(c => c.Department)
.WithMany(d => d.Courses)
.HasForeignKey(d => new { d.DepartmentID, d.DepartmentName });

Renaming a Foreign Key That Is Not Defined in the Model

If you choose not to define a foreign key on the CLR type, but want to specify what name it should have in the database, do the following:

modelBuilder.Entity()
.HasRequired(c => c.Department)
.WithMany(t => t.Courses)
.Map(m => m.MapKey(“ChangedDepartmentID”));

Configuring a Foreign Key Name That Does Not Follow the Code First Convention

If the foreign key property on the Course class was called SomeDepartmentID instead of DepartmentID, you would need to do the following to specify that you want SomeDepartmentID to be the foreign key:

modelBuilder.Entity()
.HasRequired(c => c.Department)
.WithMany(d => d.Courses)
.HasForeignKey(c => c.SomeDepartmentID);

Model Used in Samples

The following Code First model is used for the samples on this page.

using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
// add a reference to System.ComponentModel.DataAnnotations DLL
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using System;

public class SchoolEntities : DbContext
{
public DbSet Courses { get; set; }
public DbSet Departments { get; set; }
public DbSet Instructors { get; set; }
public DbSet OfficeAssignments { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// Configure Code First to ignore PluralizingTableName convention
// If you keep this convention then the generated tables will have pluralized names.
modelBuilder.Conventions.Remove();
}
}

public class Department
{
public Department()
{
this.Courses = new HashSet();
}
// Primary key
public int DepartmentID { get; set; }
public string Name { get; set; }
public decimal Budget { get; set; }
public System.DateTime StartDate { get; set; }
public int? Administrator { get; set; }

// Navigation property
public virtual ICollection Courses { get; private set; }
}

public class Course
{
public Course()
{
this.Instructors = new HashSet();
}
// Primary key
public int CourseID { get; set; }

public string Title { get; set; }
public int Credits { get; set; }

// Foreign key
public int DepartmentID { get; set; }

// Navigation properties
public virtual Department Department { get; set; }
public virtual ICollection Instructors { get; private set; }
}

public partial class OnlineCourse : Course
{
public string URL { get; set; }
}

public partial class OnsiteCourse : Course
{
public OnsiteCourse()
{
Details = new Details();
}

public Details Details { get; set; }
}

public class Details
{
public System.DateTime Time { get; set; }
public string Location { get; set; }
public string Days { get; set; }
}

public class Instructor
{
public Instructor()
{
this.Courses = new List();
}

// Primary key
public int InstructorID { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public System.DateTime HireDate { get; set; }

// Navigation properties
public virtual ICollection Courses { get; private set; }
}

public class OfficeAssignment
{
// Specifying InstructorID as a primary
[Key()]
public Int32 InstructorID { get; set; }

public string Location { get; set; }

// When the Entity Framework sees Timestamp attribute
// it configures ConcurrencyCheck and DatabaseGeneratedPattern=Computed.
[Timestamp]
public Byte[] Timestamp { get; set; }

// Navigation property
public virtual Instructor Instructor { get; set; }
}
http://msdn.microsoft.com/en-gb/data/jj591620.aspx

MVC RenderPartial pass parameters

In my ASP.NET MVC 4 partial view, I was having an issue where VaidationSummary and VaidationMessageFor were coming up blank. I scratched my head on this for quite some time. I finally came across this entry at the MVC forums at MSDN. It turns out I wasn’t passing the ViewData from parent view, but in fact my own fresh ViewData. This is how I had things before:

The Wrong Way

@{
Html.RenderPartial(“_CreateEditDisplay”, Model, new ViewDataDictionary { { “Submit”, true }, { “Action”, “Edit” }, { “ReadOnly”, false } });
}

The Right Way
I figured it out by doing this instead:

@{
Html.ViewData.Add(new KeyValuePair<string, object>(“Submit”, true));
Html.ViewData.Add(new KeyValuePair<string, object>(“Action”, “Edit”));
Html.ViewData.Add(new KeyValuePair<string, object>(“ReadOnly”, false));

Html.RenderPartial(“_CreateEditDisplay”, Model, Html.ViewData);
}

Basically what we have here is the original ViewData from the parent view with my additional add-ons that are passed to the partial view. Once I made this change, the ModelState is propagated to the partial view and VaidationSummary and VaidationMessageFor are outputting the desired results.

Entity Framework: “Store update, insert, or delete statement affected an unexpected number of rows (0).”

Entity Framework: “Store update, insert, or delete statement affected an unexpected number of rows (0).”

I ran into this and it was caused by the entity’s ID (key) field not being set. Thus when the context went to save the data, it could not find an ID = 0. Be sure to place a break point in your update statement and verify that the entity’s ID has been set.