Tag Archives: Entity Framework

A circular reference was detected while serializing an object of type

Hi All,

I am using MVC4 and Entity Framework  in my application .

I am serializing my model using JsonSerialize

the code looks like this.

        public static string Serialize(object value)
        {
            
            string formattedItem = JsonConvert.SerializeObject(value, JsonSerializationSettings.Settings);           
           
            formattedItem = formattedItem.Replace(""$type": "", ""type": "");

            return formattedItem;
        }

So I tried using 

 ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore  

   & also tried this 
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,

PreserveReferencesHandling = PreserveReferencesHandling.Objects

When I Use ReferenceLoopHandling, PreserveReferencesHandling  .. there is no circular reference error , but the Json returned is not correct .

How should I solve this problem , Could anyone please suggest .

Thanks

Hi , that link shows the simple structure , but I have a very complex structure of Parent and Child relation ,

Please suggest

Thanks

Hi gowrifor,

For the one-to-many or many-to-many relations, we can’t serialize it directly.

The easy way is that you could use ViewModel or anonymous (select new{}) type, then serialize it.

You also could refer to this article to try to do by yourself:

# Refactoring with LINQ

https://prashantbrall.wordpress.com/tag/entity-framework-and-poco/

There are some links that may benefit you:

# Serializing Entity Framework Objects into JSON Using ASP.Net MVC

http://mytechworld.azurewebsites.net/2010/02/serializing-entity-framework-objects-into-json-using-asp-net-mvc/

# JavaScriptSerializer circular reference when using ScriptIgnore

http://stackoverflow.com/questions/14569207/javascriptserializer-circular-reference-when-using-scriptignore

Best Regards

Starain Chen

[RESOLVED]Always filtering Index View on Bool Entity / Displaying only a subset of data

I would like to have the index view (code below) always filter the data on a bool entitiy so that only a subset of the database displays – not the entire database.

If anyone could point me in the right direction, I would appreciate it.

Index.cshtml

@model PagedList.IPagedList<GenericWebApplication.Models.Class_EntitySet01>
@using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />

@{
    ViewBag.Title = "Class_EntitySet01";
}

<h2>Class_EntitySet01</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>

@using (Html.BeginForm("Index", "Class_EntitySet01", FormMethod.Get))
{
    <p>
        Find by name: @Html.TextBox("SearchString", ViewBag.CurrentFilter as string)
        <input type="submit" value="Search" />
    </p>
}

<table>
    <tr>
        <th>
            @Html.ActionLink("Last Name", "Index", new { sortOrder = ViewBag.NameSortParm, currentFilter = ViewBag.CurrentFilter })
        </th>
        <th>
            First Name
        </th>
        <th>
            @Html.ActionLink("Enrollment Date", "Index", new { sortOrder = ViewBag.DateSortParm, currentFilter = ViewBag.CurrentFilter })
        </th>
        <th></th>
    </tr>

        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Property_Entity01)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Property_Entity02)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Property_Entity21)
        </td>

        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })
        </td>
    </tr>
}

</table>

<br />
Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount

@Html.PagedListPager(Model, page => Url.Action("Index",
    new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))

Class_EntitySet01Controller.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using GenericWebApplication.Models;
using GenericWebApplication.DAL;
using PagedList;
using System.Data.Entity.Infrastructure;

namespace GenericWebApplication.Controllers
{
    public class Class_EntitySet01Controller : Controller
    {
        private GenericWebApplicationContext db = new GenericWebApplicationContext();

        // GET: /Class_EntitySet01/
        public ActionResult Index(string sortOrder, string currentFilter, string searchString, int? page)
        {
            ViewBag.CurrentSort = sortOrder;
            ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
            ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";

            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewBag.CurrentFilter = searchString;           
            
            
            var class_entityset01s = from s in db.Class_EntitySet01s
                           select s;

            if (!String.IsNullOrEmpty(searchString))
            {
                class_entityset01s = class_entityset01s.Where(s => s.Property_Entity01.ToUpper().Contains(searchString.ToUpper())
                                       || s.Property_Entity02.ToUpper().Contains(searchString.ToUpper()));
            }
            
            switch (sortOrder)
            {
                case "name_desc":
                    class_entityset01s = class_entityset01s.OrderByDescending(s => s.Property_Entity01);
                    break;
                case "Date":
                    class_entityset01s = class_entityset01s.OrderBy(s => s.Property_Entity21);
                    break;
                case "date_desc":
                    class_entityset01s = class_entityset01s.OrderByDescending(s => s.Property_Entity21);
                    break;
                default:
                    class_entityset01s = class_entityset01s.OrderBy(s => s.Property_Entity01);
                    break;
            }

            int pageSize = 3;
            int pageNumber = (page ?? 1);

            return View(class_entityset01s.ToPagedList(pageNumber, pageSize));
        }

        // GET: /Class_EntitySet01/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Class_EntitySet01 class_entityset01 = db.Class_EntitySet01s.Find(id);
            if (class_entityset01 == null)
            {
                return HttpNotFound();
            }
            return View(class_entityset01);
        }

        // GET: /Class_EntitySet01/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: /Class_EntitySet01/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Property_Entity01,Property_Entity02,Property_Entity21")] Class_EntitySet01 class_entityset01)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    db.Class_EntitySet01s.Add(class_entityset01);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
            catch (RetryLimitExceededException /* dex */)
            {
                //Log the error (uncomment dex variable name and add a line here to write a log.
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
            }
            return View(class_entityset01);
        }

        // GET: /Class_EntitySet01/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Class_EntitySet01 class_entityset01 = db.Class_EntitySet01s.Find(id);
            if (class_entityset01 == null)
            {
                return HttpNotFound();
            }
            return View(class_entityset01);
        }

        // POST: /Class_EntitySet01/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "ID,Property_Entity01,Property_Entity02,Property_Entity21")] Class_EntitySet01 class_entityset01)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    db.Entry(class_entityset01).State = EntityState.Modified;
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
            catch (RetryLimitExceededException /* dex */)
            {
                //Log the error (uncomment dex variable name and add a line here to write a log.
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
            }
            return View(class_entityset01);
        }

        // GET: /Class_EntitySet01/Delete/5
        public ActionResult Delete(int? id, bool? saveChangesError = false)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            if (saveChangesError.GetValueOrDefault())
            {
                ViewBag.ErrorMessage = "Delete failed. Try again, and if the problem persists see your system administrator.";
            }
            Class_EntitySet01 class_entityset01 = db.Class_EntitySet01s.Find(id);
            if (class_entityset01 == null)
            {
                return HttpNotFound();
            }
            return View(class_entityset01);
        }

        // POST: /Class_EntitySet01/Delete/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Delete(int id)
        {
            try
            {
                Class_EntitySet01 class_entityset01 = db.Class_EntitySet01s.Find(id);
                db.Class_EntitySet01s.Remove(class_entityset01);
                db.SaveChanges();
            }
            catch (RetryLimitExceededException /* dex */)
            {
                //Log the error (uncomment dex variable name and add a line here to write a log.
                return RedirectToAction("Delete", new { id = id, saveChangesError = true });
            }
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}

__________________________________________________________________

Programming Environment:

    Visual Studio 2013
    .NET 4.5
    Entity Framework 6 (EntityFramework 6.1.0 NuGet package)
    OS: Windows 7

Project Based On:
Getting Started with Entity Framework 6 Code First using MVC 5

http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application

var class_entityset01s = from s in db.Class_EntitySet01s
                           where s.SomeField == true
                           select s;

Thank you SO much!

[RESOLVED]Newbie intern: A little lost on how to structure and get my project started (updating DB tables with an SPA)

Hi all,

So here are the details of the project that I have been assigned:

The company has several database tables which I am to make accessible via a webpage, and users that are properly authenticated should be able to go in, select the appropriate table from a drop-down and then edit the relevant row. The updates should then
be send back to the database. They already have a web project going that uses Web-Api as a backend with angular.js as a front-end, and I’d like to make mine as compatible as that so that it could eventually be integrated within. 

Initially, I thought to use strongly typed models using the ado.net data object model, but what if they want to dynamically add a new table to the list in the drop down? Would I not have to go into my code, and always explicitly add a new model to accommodate
this? Is there a way to dynamically handle any new table (perhaps by not using Entity Framework)?

If you need more details, just let me know. How would you more experienced programmers handle this?

Thanks in advance, any advice would be appreciated! :)

ZimbuTheMonkey

t what if they want to dynamically add a new table to the list in the drop down?

use DataTable. Or use plugin architecture and add dll’s to the project.

What you need is some kind of meta data driven approach, where you dynamically get the tables and their columns from the database and allow user to update them. Please see this example which is done for WPF. You can easily adopt for a web application

Dynamic Data Entry With XML Literals

Thank you, I’ll have a look.

[RESOLVED]Entity framework, DB first approach, update code based on changes in DB but saving modifications made by progammer

I updated my database(added a new table), and used Entity framework to propagate changes to the code.  It worked alright except all my modifications e.g. attributes I added to some classes  were undone. Is there a way to keep the changes made by the programmer
and still do updates using Entity Framework? In other words, prevent some model classes from getting updated and only update certain classes?

Thanks,

Rose

Yes, if you look closely at the generated work from EF you’ll see almost everything is a partial class which means you can add stuff in a partial that will not get overwritten.  Consider the EF part a project of it’s own that’s solely dedicated to the DB/Application
layer interface, look at it as a Mediator and NOT an implementation of other concerns.  It’s sole purpose it to 1) Map DB relationships and 2) To be a close if not exact model of the DB layer.  You can create classes there that inherit from other classes or
implement interfaces or even contain other Entity types, but make sure to create a folder and keep all the generated stuff separate from your custom stuff.

Then in the application project all you need to do is reference the entity project to write your queries.  Some take this even a step further by creating what they call a "repository", but for simplicity in get started just put all your queries in a folder
in application project.  I often make them all static methods so the upper layers of the application (such as a viewmodel) can do things like this:

DataLayer.GetCustomers();
DataLayer.GetCustomer("somelastname");
DateLayer.SaveCustomer(customerinstance);
...

You can see the simplicity at the upper app. layers of this pattern…

One other note, and a personal choice for me, I handle all exceptions in the data layer, not in the Entity project.  Why?  Because its the application that wants the data, let the applications’ data layer do error handling.  

What you want to do is create Meta Data classes for the tables that have fields you want to add attributes to.  For example, say you have a table called County and this is the class that Entity Framework generated for you:

public partial class County
    public int CountyId { get; set; }
    public string Name { get; set; }
}

Create another file called CountyMetaData.  Make sure it has the same namespace as the County class:

[MetadataType(typeof(CountyMetaData))]
public partial class County
{
    // Here you can define any additional properties that are not mapped to your database,
    // such as calculated fields.
}
       
public class CountyMetaData
{
    // Here re-define any properties that you want to add attributes to.

    [Display(Name = "County")]
    [MaxLength(50)]
    [Required(ErrorMessage = "*")]
    public string Name { get; set; }
}

When Entity Framework propagates the changes, it won’t touch the CountyMetaData class, so your attributes will not be lost.

[RESOLVED]Where to place Model classes

Hi I created an ASP.NET MVC 4 Razor Internet Application.

I’ve generated the Model Classes from an existing SQL Server Database.

Then I generated an MVC Controller with read/write actions and views using Entity Framework.

That generated Views for all CRUD methods and a MySystemModel.emdx folder

Inside that folder there are

MySystemModel.Context.tt
MySystemModel.Designer.cs
MySystemModel.edmx.diagram
MySystemModel..tt

Inside MySystemModel..tt there are classes for all tables I have in the database plus a MySystemModel.cs:

TABLE1.cs
TABLE2.cs
TABLE3.cs
MySystemModel.cs

Now here is where I got confused:

I still have a MODELS folder that MVC created in the beginning, altogether with CONTROLLERS and VIEWS and other folders.

Usually in this foder I would place the table properties if I was using a CODE FIRST approach.

I would use a Table1Model.cs class for example to set some DataAnnotations attributes such as:

[Required]
[EmailAddress]
[StringLength(200)]
[Display(Name="Email address")]

public string Email { get; set; }

Question: Should I place these validations in:

A)      the generated classes inside MySystemModel.emdx folder

B)       MVC MODEL folder (in this case I would have to recreate them)

I know it can work different ways but I would like to know what the best practices are.

I’ve also seen some examples where the MODEL was a whole different project (perhaps a class library?) inside the solution.

So I am confused how can these Models be in different places.

Thanks

<div class="comment-right-col">

</div>

skynyrd

Question: Should I place these validations in:

The answer is B, the Models folder.  And not only that, but you "should not" add annotations to auto-generated classes.  The reason for this is that if you decide to change a db column in any way, you’ll lose those annotations when you re-generate the models
for your db.

Instead, you should use what’s called "Meta Data" classes.  These classes are mapped to your generated classes, but do not change should you need to re-generate your db models.

I had a post somewhat recently on creating these classes, but I cannot find it.  sorry

The easy answer is the Models folder. However, I think additional separation of concerns is good and place my models in their own project. I then use View Models in the Web project.

You can use partial "buddy" classes for your annotations. 

public partial class Table1Model.cs
{
[Required]
[EmailAddress]
[StringLength(200)]
[Display(Name="Email address")]

public string Email { get; set; }
}

You can put these in your Models folder. See this for more information on buddy classes: http://www.asp.net/mvc/tutorials/older-versions/getting-started-with-mvc/getting-started-with-mvc-part7

skynyrd

the generated classes inside MySystemModel.emdx folder

These are the domain models and you typically should not expose to the UI layer. So create a similar model (including only the properties needed for the view) in the Model class. Here you can define your attributes. Sometimes the models in the Model folder
is called as ViewModels as they may map to multiple domain models.

Hi,

You need another partial class. Normally this new partial class using the same name with it’s model class. Here we can not make it on the same folder. In this case I add one more folder only for validation. Like the first reply your do not change any model
class on .edmx because it generated automatically and update when it needed. Say on Models folder add a "partial" folder, and change the partial class nameSpace without "partial" folder",

Here the example: new partial class on "partial" folder, where this "partial" folder is in "Models" folder: 

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PersonEntity.Models
{
    [MetadataType(typeof(ProductMetadata))]
    public partial class Product
    {
    }
    public class ProductMetadata
    {
        [DisplayFormat(NullDisplayText = "n/a")]
        [Display(Name = "Product Name")]
        public string Name { get; set; }
    }
}

And this is the auto generated class under .edmx on "Models" folder

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace PersonEntity.Models
{
    using System;
    using System.Collections.Generic;
    
    public partial class Product
    {
        public Product()
        {
            this.BillOfMaterials = new HashSet<BillOfMaterial>();
            this.BillOfMaterials1 = new HashSet<BillOfMaterial>();
            this.ProductCosts = new HashSet<ProductCost>();
            this.ProductCostHistories = new HashSet<ProductCostHistory>();
            this.ProductDocuments = new HashSet<ProductDocument>();
            this.ProductListPrices = new HashSet<ProductListPrice>();
            this.ProductListPriceHistories = new HashSet<ProductListPriceHistory>();
            this.ProductReviews = new HashSet<ProductReview>();
            this.ProductPhotoSets = new HashSet<ProductPhotoSet>();
            this.ProductDescriptions = new HashSet<ProductDescription>();
            this.ProductInventories = new HashSet<ProductInventory>();
        }
    
        public int Id { get; set; }
        public string Name { get; set; }
        public string ProductNumber { get; set; }
        public string CompatibleProductNumber { get; set; }
        public bool MakeFlag { get; set; }
        public bool FinishedGoodsFlag { get; set; }
        public string Color { get; set; }
        public short SafetyStockLevel { get; set; }
        public short ReorderPoint { get; set; }
        public decimal StandardCost { get; set; }
        public decimal ListPrice { get; set; }
        public Nullable<decimal> Size { get; set; }
        public string SizeUnitMeasureCode { get; set; }
        public string WeightUnitMeasureCode { get; set; }
        public Nullable<decimal> Weight { get; set; }
        public int DaysToManufacture { get; set; }
        public string ProductLine { get; set; }
        public string Class { get; set; }
        public string Style { get; set; }
        public Nullable<int> ProductCategoryID { get; set; }
        public Nullable<int> ProductModelID { get; set; }
        public System.DateTime SellStartDate { get; set; }
        public Nullable<System.DateTime> SellEndDate { get; set; }
        public Nullable<System.DateTime> DiscontinuedDate { get; set; }
        public System.DateTime ModifiedDate { get; set; }
    
        public virtual ICollection<BillOfMaterial> BillOfMaterials { get; set; }
        public virtual ICollection<BillOfMaterial> BillOfMaterials1 { get; set; }
        public virtual ProductCategory ProductCategory { get; set; }
        public virtual UnitMeasure UnitMeasure { get; set; }
        public virtual UnitMeasure UnitMeasure1 { get; set; }
        public virtual ICollection<ProductCost> ProductCosts { get; set; }
        public virtual ICollection<ProductCostHistory> ProductCostHistories { get; set; }
        public virtual ICollection<ProductDocument> ProductDocuments { get; set; }
        public virtual ICollection<ProductListPrice> ProductListPrices { get; set; }
        public virtual ICollection<ProductListPriceHistory> ProductListPriceHistories { get; set; }
        public virtual ICollection<ProductReview> ProductReviews { get; set; }
        public virtual ICollection<ProductPhotoSet> ProductPhotoSets { get; set; }
        public virtual ICollection<ProductDescription> ProductDescriptions { get; set; }
        public virtual ICollection<ProductInventory> ProductInventories { get; set; }
    }
}

Summary:

Validation for Product.cs is under "PersonEntity.Models.Partial",

Auto generate for Product.cs is under "PersonEntity.Models"

Both Product.cs has the same NameSpace at the example is "namespace PersonEntity.Models"

This is the way I do. That example is my real project.

Have fun

Great stuff guys.

I am using this Metadata classes and they work great.

I don’t even have to copy all the properties into them, just the ones I want to set some attributes.

Thanks!

Hi,

We also can add a new "Read Only" property on the new partial class, look at the following example. This additional property does not have any effect on database table. We can directly use "FullName" in our business logic. This is the beauty of partial class
and help me a lot reducing coding in both client side and server side.

Here additional partial class:

using System.ComponentModel.DataAnnotations;

namespace PersonEntity.Model
{
    [MetadataType(typeof(PersonMetadata))]
    public partial class Person
    {
        [Display(Name = "Full Name")]
        public string FullName
        {
            get
            {
                string fullName = string.Empty;
                if (NameStyle)
                    fullName = ((FirstName + " " + MiddleName).Trim() + " " + LastName).Trim();
                else
                {
                    fullName = LastName == string.Empty || LastName == null ? string.Empty : (LastName + " " + MiddleName).Trim();
                    fullName = fullName == string.Empty ? FirstName : (fullName + ", " + FirstName).Trim();
                }

                return fullName;
            }
        }

        public class PersonMetadata
        {
            [StringLength(25, ErrorMessage = "First name must be 25 characters or less in length.")]
            [Required(ErrorMessage = "First name is required.")]
            public string FirstName { get; set; }
        }
    }
}

This FullName property is depending on NameStyle, FirstName, MiddleName, and LastName. It also cover eastern name style, and western name style automatically. Again there is no effect on database side.

Here the auto generated class:

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace PersonEntity.Model
{
    using System;
    using System.Collections.Generic;
    
    public partial class Person
    {
        public Person()
        {
            this.Attendances = new HashSet<Attendance>();
            this.Sessions = new HashSet<Session>();
            this.FactComments = new HashSet<FactComment>();
            this.FactFindings = new HashSet<FactFinding>();
            this.FactFindings1 = new HashSet<FactFinding>();
            this.FactFindings2 = new HashSet<FactFinding>();
        }
    
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public string LastName { get; set; }
        public string NickName { get; set; }
        public Nullable<int> PersonTypeId { get; set; }
        public bool NameStyle { get; set; }
        public string Title { get; set; }
        public string Suffix { get; set; }
        public string Phone { get; set; }
        public string Email { get; set; }
        public string Blog { get; set; }
        public string Twitter { get; set; }
        public string Gender { get; set; }
        public string ImageSource { get; set; }
        public string Bio { get; set; }
        public int PersonCategoryId { get; set; }
        public System.DateTime BirthDate { get; set; }
        public string MaritalStatus { get; set; }
        public System.DateTime DateAdd { get; set; }
        public string AdditionalContactInfo { get; set; }
        public string Demographics { get; set; }
        public System.Guid RowGuid { get; set; }
        public System.DateTime ModifiedDate { get; set; }
        public bool IsLocked { get; set; }
    
        public virtual ICollection<Attendance> Attendances { get; set; }
        public virtual ICollection<Session> Sessions { get; set; }
        public virtual ICollection<FactComment> FactComments { get; set; }
        public virtual ICollection<FactFinding> FactFindings { get; set; }
        public virtual ICollection<FactFinding> FactFindings1 { get; set; }
        public virtual ICollection<FactFinding> FactFindings2 { get; set; }
    }
}

Have fun

[RESOLVED]using RDLC in MVC projects

We have a MVC 4.0 project and for reporting we used RDLC. We need to have the reportviewer control available in client page, because we want our web application to be very similar with a desktop application.

To work with RDLC we have to use aspx pages inside our project which are loaded inside iframe based on src=… path.

We store these files in Reports folder inside our project.

Everything was working in our development process. We use Visual Studio 2013 with IIS Express.

When we have done the deployment to the production server, we observe that our reports are not working. We receive the 404 error. We have received the same 404 error from Windows Server 2008 SBS and from Windows Server 2012 Standard where we have made the
deployment

Please help us with this issues.

Thank you very much

You may look into using the Reports as "Local Reports" and simply using MVC to render them via their path (instead of navigating to them directly, which would require routing changes). I recently implemented a similar structure to support accessing
data via Entity Framework to populate to populate a few RDLC Reports that I had created. Although this may not be exactly the approach that I took, I would recommend

taking a look at this blog post on the topic
.

If you don’t want to take that approach and would prefer to render an actual Report Viewer directly within an MVC View (or navigate to an ASPX page that contained your report), you might be better off using an approach
like this one.

Hi horia,

First, please refer to Rion’s reply.

Secondly, please use
Server.MapPath
to generate the path dynamically.

On the other hand, there are some articles about report that can help you:

# ASP.NET MVC Html Helpers for ReportViewer Control.

https://github.com/ilich/MvcReportViewer

# Prototype MVC4 Razor ReportViewer? RDLC

http://www.codeproject.com/Articles/609580/Prototype-MVC-Razor-ReportViewer-RDLC

Best Regards

Starain Chen

if you have internet explorer greater than I.E 8. There is something called developer tools (press F12). on network tab you can start monitoring.

Find the url which is giving 404. Hit the url separately from new tab in the browser, check if you are getting the same 404.

Find the url which is working in you dev environment, get the url from there. Find the difference between working and non working url. It could be because of cross posting, domain bieng different, url bieng wrong, insufficient file permission for files in
reports folder. If there are physical file, you might also want to set it up as static file at IIS level or in web.config

In the first approach I can not see report toolbar at client. I want that client to be able to navigate from page to page, choose option to export in XLS, PDF.Doc, to be able to print and to choose the printer like in desktop application.

second approach I have to test in the next days and I will let you know.

But I have one very logical question. Why it is working in developing with IIS Express and is not working in production server with IIS. For me this is unbelievable.

Thanks for reply

Of course I have tried with network monitoring and the same path in the IIS express is working fine, but In production environment IIS give 404 error.

IIS Express example:

<iframe width="99.5%" height="99%" id="myReport" src="….ReportsRaportDocumentIesire.aspx?idSucurs=219bc74c-1ab6-11d4-b1e8-00a0d21052ef&amp;idDocument=fcc247d8-ae2a-49f1-ae74-1ac063606932&amp;Format=FACT&amp;lcnrZecimaleCantitate=3&amp;lcnrZecimalePret=2&amp;lcnrZecimaleValuta=2"
frameborder="1"></iframe>

URL Method Result Type Received Taken Initiator Wait‎‎ Start‎‎ Request‎‎ Response‎‎ Cache read‎‎ Gap‎‎
/Reports/RaportDocumentIesire.aspx?idSucurs=219bc74c-1ab6-11d4-b1e8-00a0d21052ef&idDocument=fcc247d8-ae2a-49f1-ae74-1ac063606932&Format=FACT&lcnrZecimaleCantitate=3&lcnrZecimalePret=2&lcnrZecimaleValuta=2 GET 200 text/html 58.79 KB 0.67 s frame
navigate 2465 0 655 16 0 1014

is working well

 

IIS production server example:

<iframe width="99.5%" height="99%" id="myReport" src="….ReportsRaportDocumentIesire.aspx?idSucurs=219bc74c-1ab6-11d4-b1e8-00a0d21052ef&amp;idDocument=fcc247d8-ae2a-49f1-ae74-1ac063606932&amp;Format=FACT&amp;lcnrZecimaleCantitate=3&amp;lcnrZecimalePret=2&amp;lcnrZecimaleValuta=2"
frameborder="1"></iframe>

URL Method Result Type Received Taken Initiator Wait‎‎ Start‎‎ Request‎‎ Response‎‎ Cache read‎‎ Gap‎‎
/Reports/RaportDocumentIesire.aspx?idSucurs=219bc74c-1ab6-11d4-b1e8-00a0d21052ef&idDocument=fcc247d8-ae2a-49f1-ae74-1ac063606932&Format=FACT&lcnrZecimaleCantitate=3&lcnrZecimalePret=2&lcnrZecimaleValuta=2 GET 404 text/html 1.70 KB 125 ms frame
navigate 63 0 125 0 0 13634

 

If we are looking to the calling path in  both cases are the same. The entire structure of the folders were copied from development server to the production. No good results.

Any idea?

Thank you.

 

Tkank you for your reply. I will begin to study again this approach and compare with article which you recommended.

Thank you

[RESOLVED]Data annotation validation

Hi
I have two questions regarding the data annotation validation.

1. Can you change the look og how the error message i show. Maybe use some of my own html
2. Can i use data annotation validation with viewmodels? I know that i can put data annotation on the attributes of my viewmodels but is it the way to go?

Hope someone can help
Jakobjensen

Yes, in Viewmodels you can implement the INotifyableObject interface.  MVC will call this implementation just before the post back enters the controller to validate anything you want. There are two modes to validation 1) For the Models itself using data
annotations and 2) And any custom business rules you need to implement in the View model.  To notify the view, the ViewModel validate method will return a collection of <ViewResult>  if you use the "Yield return new ViewResults("blah, blah blah")" construct
you can write as many validation rules as you need an very easily send them to the view.  

Reminder, make sure you set up something like @Html.ValidationSummry(true or false) up in the view in order to see them.  One final note, any Action method checking for Model.ViewState is valid any bypassing logic, will force those errors to be fixed!  In
other words it is a controller decision on what to do, however, why set up exception parsing rules for this if you just need to warn the user of something rather than forcing a correction.  For warning messages you are better off implementing on client side.
 Just create a hidden field or dialog that pops up from using JQuery or Javascript for those.

Can you change the look?  Anything is possible if you implement the entire system yourself or use JavaQuery to manipulate the DOM after document.ready.  You’ll easily be able to spot what MVC does to generate those messages.  Jquery can do anything with
them. 

Thanks for the answer.

So the way i do now is that i have some homemade javascript to handle client side validation.
And then i want to use entity frameworks serverside validation.
How do i make entity framework talk with my javascript.
I want the same error to show up both for client side errors and for server side errors

Im not sure i made myself clear…
I want to validate with the annotation from my business classes.
I have viewmodels.
And i have some javascript that validates and thats fine by me. But i dont know how to handle to kind of validation..

Lets say the user enters something wrong. Then he see my error message from javascript.

But if he has javascript disabled he should see the message from entity framework.

How do you handle these to validation?

Hi Jakobjensen,

jakobjensen

Can you change the look og how the error message i show. Maybe use some of my own html

I suggest that you could specify the style in the parent element, such as:

<div style="..."> 
@Html.ValidationMessageFor(m => m.UserName)
</div>

You also could custom HtmlHelper to custom it.

# Custom ValidationSummary template Asp.net MVC

http://stackoverflow.com/questions/5857851/custom-validationsummary-template-asp-net-mvc-3

jakobjensen

Can i use data annotation validation with viewmodels? I know that i can put data annotation on the attributes of my viewmodels but is it the way to go?

You just need add the data annotation validation attribute to the fields or properties of the
ViewModels.

Best Regards

Starain

Hi,

1. Use CSS style, what you want.

2. Custom Data Annotation always good, beco’z you can push your logic into validation.

http://20fingers2brains.blogspot.com/2013/04/custom-annotations-in-aspnet-mvc3-razor.html

Thanks,

Jai.

[RESOLVED]How to learn MVC well?

Hi guys ,

    Recently I was asked to handle a project using MVC5. I’m a fresh man of Asp.net , and before I try to learn Asp.net WebForm an exported who has plenty asp.net developing exprience told me that I’d better jump over the traditional WebForm, and start to
learn MVC directly. Well I’ve learned this "http://www.asp.net/mvc/tutorials/mvc-5/introduction/getting-started"  and tried the whole sample. But where should I put my right
foot after that ? I know that I’m still far away from a MVC developer, but what I should learn next ? How many things else I need to know before I can use MVC to build a site like this one ?

Thanks for any suggestion :)

I am currently learning MVC modern framework. Do you have a project at work you are working on? If not, no worries, more time for you to learn on your own (I hope). Please take a peak at the Adam Freeman books. See here: http://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=Pro+ASP.NET+MVC+5 I
am currently going through them. It will take time. Most importantly, can you think of a cool custom project you want to do? Even if you don’t know how to code the features. Try to build your idea piece by piece. As many Microsoft developers have commented
on their own tutorials, we should really try to learn by doing. 

I am constantly looking for more tutorials and materials myself. My current challenge is finding decent resources for authentication. Hang in there. :) 

Hlyates, what about authentication are you trying to find resources for? Maybe I can help!

Hey Robin,

An enterprise level MVC application would probably use some of the following:

Client Side:

  • HTML
  • CSS
  • jQuery
  • Javascript
  • Ajax

Server Side:

  • .NET MVC
  • C#
  • SQL
  • Entity Framework

Some other general things that will help along the way:

  • Security
  • Continuous Integration and Deployment
  • Caching
  • Client and Server side debugging tools
  • Unit/Integration/Acceptance testing

I was thinking of creating something that helped people create an Enterprise grade website from scratch. This would help you learn all of the skills, at least at a high level, and also have something to add to your portfolio for jobs.

Does that sound like something you would be interested in/that would be useful?

Steve

Just ask here in the forums if you don’t understand something. And do a lot of research
Smile

stephenmichaelf7

Hlyates, what about authentication are you trying to find resources for? Maybe I can help!

Anything that I can find that is MVC 5. I would like to find source code to study and tutorials. Please read my post

here
. As for making tutorials yourself, yes, anything you would like to share helps. Additionally, any resources to help learn HTML/CSS/JQuery/JavaScript for ASP.NET MVC specifically?

Hi Robin,

Thanks for your post.

Robin20091010

I’m a fresh man of Asp.net

I suggest that you can follow this tutorial:

http://www.asp.net/mvc/tutorials/mvc-music-store and you can download the completed code to learn

Hope this can be helpful.

Best Regards,

Eileen

Hi Steve,

Many thanks 2u man! That’s almost the perfect answer I’m looking for! 

Also I’m thinking about that maybe I need a "more complicated" sample for me to learn to.

Actually in the past few year I’ve majored in Winform development using C#, so I think I’m kinda familiar with C#/MsSql/CI/UnitTest methodoloies,but web developing skills are always my weakness :(    Recently I’ve learned by myself HTML/CSS/Javascript, yet
cannot expertly to use those three. So my question after I finished the "Getting Start Sample" was how to use MVC to create an excellent/good looking page…like some popup dialogs or something else to make it more "professional" , or as "Enterprise grade
" like you said. I have a little experience on WebForm developing, but it doesn’t help me at all. Anyway, thanks for your advise so much!

Have a nice day, thank you again :)

Robin.

Hi Eileen,

Thanks very much.It’s a good suggestion for me. I’ll check it out immediately!!!

Robin.

Hi hlyates,

Thanks very much!

"Do you have a project at work you are working on" — yes, it’s coming soon to me in 1 week :( 

Anyway, I would like to read that book you recommend to me ASAP.

Have a nice day :)

Hey Robin,

The quickest way to get started with design is to use Bootstrap, which is actually included in new MVC projects.

You can find it here:

http://getbootstrap.com/

It sounds like there are two different things you are asking for.

The first is the skill of HTML/CSS/Javascript, and the second is how to design and make things look professional.

While they are related they are also two different things.

What resources have you used for HTML/CSS/Javascript? For design, check out this book:

Design For Hackers

It goes over the main design principles for developers.

Steve

Hello Stephen,

Again, thanks for you suggestion.

Well , I basically learned Front-end developing skills from W3CSchool site and a book "javascript professional", and I tried a lot of tiny demos, but that’s far away to be called professional. I agree with you about " two different things you are asking
for
" and yes, both of those two are my weakness :(  

Maybe I asked that in a wrong way, I think actually I’m wondering if there’re some examples for me to understand how could I create an "enterprising" website with asp.net MVC. 

As you may know, with Asp.net, it’s a little bit easier to create an aspx webform page contains a popup window, or some cool/good-looking things, because the web controllers make it easy to do so. I guess it’s not a good way to develop any web applications
with web controller, but with MVC, eh…I don’t know how to arrange my page at all. The reason I like the artical "Getting started with mvc5" so much is the author introduce me a lot of basic knowledge about MVC through a simple demo. But I still have many
questions about MVC and don’t know what kind of things I need to know deeper for the coming project :( And that’s why I post my question here for help.

Anyway, thank you sooooo much! Have a nice day man :)

Robin.

[RESOLVED]Generating seed from an existing database

Hello I have a code first entity framework project. The project is ready to be deployed but unfortunately it already contains data that cannot be erased. How can I deploy without loosing this data. My guess was to generate a seed method from the existing
data, but the question is: How do I do that?

Thanks

Hi,

And you can’t deploy the db file? For example doing  a backup/restore operation to restore the initial db to your production configuration? See perhaps the documentation for your host service?