Creating Inheritance Relationships in Entity Framework

by Admin 12. June 2013 06:03

To implement Inheritance relationships, first let the EF wizard generate your its default entities from your tables. Then right-mouse click on the EF designer and select Add | Entity.  In the resulting dialog, give your new entity a name (e.g., "PremiumService") and specify that it inherits from an existing class (e.g., "Service") using the Base type dropdown list. You can then cut and paste properties from one class to another (e.g. does the "DiscountRate" only apply to PremiumServices? Then select that property in the Service class, cut it, and paste it into the PremiumService's properties).

You won't be instantiating the original, base class entity in code anymore, so select it, and in its Properties Window, set its Abstract property to True (i.e. from now on I'll use PremiumService or TypicalService, but not Service, so I make the Service entity abstract).

Now you need to tell EF about your type column so it will know when to create the right object. Right-mouse click on one of your new classes (e.g., PremiumService) and select Table Mapping to display the mappings between table columns (on the left) and entity properties (on the right); right now the mapping table will be empty. Click on <Add Table or View> and select your table (e.g., Services) to tie the table your new entity. Click on the new <Add a Condition> choice and select your type column. In the Value/Property column, enter the data that identifies the row (if it's a string value, make sure you put quotes around the value). Repeat for your other new entities. Finally, delete your type column from your base table -- EF will take of making sure it's set correctly.

And you're done! You now have several classes managing a single table, but the right class will be generated for you at the right time by EF (and, when it adds new rows to your table, it will make sure that your type column is updated correctly). You also have less logic to design because you just have to put the code appropriate for each entity in each of your entities.

Tags:

Creating Inheritance Relationships in Entity Framework VS 2012

by Admin 12. June 2013 06:03

To implement Inheritance relationships, first let the EF wizard generate the default entities from the tables. Then right-mouse click on the EF designer and select Add | Entity.  In the resulting dialog, give your new entity a name (e.g., "PremiumService") and specify that it inherits from an existing class (e.g., "Service") using the Base type dropdown list. You can then cut and paste properties from one class to another (e.g. does the "DiscountRate" only apply to PremiumServices? Then select that property in the Service class, cut it, and paste it into the PremiumService's properties).

You won't be instantiating the original, base class entity in code anymore, so select it, and in its Properties Window, set its Abstract property to True (i.e. from now on I'll use PremiumService or TypicalService, but not Service, so I make the Service entity abstract).

Now you need to tell EF about your type column so it will know when to create the right object. Right-mouse click on one of your new classes (e.g., PremiumService) and select Table Mapping to display the mappings between table columns (on the left) and entity properties (on the right); right now the mapping table will be empty. Click on <Add Table or View> and select your table (e.g., Services) to tie the table your new entity. Click on the new <Add a Condition> choice and select your type column. In the Value/Property column, enter the data that identifies the row (if it's a string value, make sure you put quotes around the value). Repeat for your other new entities. Finally, delete your type column from your base table -- EF will take of making sure it's set correctly.

And you're done! You now have several classes managing a single table, but the right class will be generated for you at the right time by EF (and, when it adds new rows to your table, it will make sure that your type column is updated correctly). You also have less logic to design because you just have to put the code appropriate for each entity in each of your entities.

 

Here is a link on this from msdn

http://msdn.microsoft.com/en-us/data/jj519700.aspx

 

 

Inheritance Relationships in Entity Framework Flow Diagram

EF5_Inheritance.gif (40.49 kb)

Tags:

July 2018 Tenants maintenance

by Admin 21. May 2013 11:28

 

 

 

 

Tags:

MVC httpcontext.current.session is null

by Admin 26. April 2013 08:21

I have come across teh issue while working with MVC3/ MVC4

Basically I am setting the session in the controller like this

 HttpContext.Session["UserAccount"] = userAccountEntityValue;

Now when I try to access the session from my class file like 

if (HttpContext.Current.Session["UserAccount"] != null)

The session fails to store the values.

Solution:

Add the following in the class file 

1. using System.Web.SessionState;

2. Inherit the class from IRequiresSessionState

     public class GlobalUtil : IRequiresSessionState

Now the error should be resolved and the session will work as expected.

Hope this helps!

Tags:

MVC4 Membership with SQL Server database

by Admin 25. April 2013 04:31

As most you guys know the membership approach has changed in MVC4 compated to MVC3 & the old ASP.NET web approach.

MVC4 uses simpleMembership and by default creates a light weight database locally within the application.

If you want to use a SQL Server database and not a local database. Here is what you need to do.

Step1: Create a database using SSMS. In this sample my database name is FastpathDesign

Step2: Add the connectionstring in the web.config

     (a) Windows Mode

<add name="FastpathDesignConnectionString" connectionString="Data Source=(local);Initial Catalog=FastpathDesign;Integrated Security=True" providerName="System.Data.SqlClient" />

     (b) SQL Server Mode

<add name="FastpathDesignConnectionString" connectionString="Data Source=my-hosting-panel.com;Initial Catalog= FastpathDesign ;User ID=fastpath_venkat;Password=yourpassword" providerName="System.Data.SqlClient" />

 

Now you can run your MVC4 application for the first time and click on the Register link, it will automatically create membership tables in SQL Server database. 

If you still got issues getting the membership tables created. You can download the script from the attachment and run it against your database.

Database Script  MVC4Membership.sql (4.07 kb) 

Note: If you get an error saying default connection cannot be found replace the name="FastpathDesignConnectionString" with  name="DefaultConnection"

Hope this helps!

Tags:

return content / text from controller in MVC3

by Admin 4. April 2013 07:39

return Content("thanks for submitting", "text/plain");

Tags:

mvc3 Caching

by Admin 4. April 2013 07:36

HttpContext.Cache.Add("CountryId", model.SelectedCountryId, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 60, 0),   System.Web.Caching.CacheItemPriority.Normal, null);

 

if (HttpContext.Cache.Get("CountryId") != null)

 countryIdValue = Convert.ToInt32(HttpContext.Cache.Get("CountryId"));

Tags:

Radio button list in ASP.NET MVC3

by Admin 25. March 2013 09:14

Country View Model

public class CountryVM

    {

        public int CountryID { get; set; }

        public string CountryCode { get; set; }

        public string CountryName { get; set; }

        public int BCRegionID { get; set; }

        public int DefaultLanguageID { get; set; }

        public int SourceID { get; set; }

        public bool Active { get; set; }

    }

Countries View Model

public class CountriesVM

    {

        public List<CountryVM> listCountries { get; set; }

        [Required]

        public int? SelectedCountryId { get; set; }

    }

 

Controller Action

public ActionResult UserCountries()

        {

            LdapServiceClient ldapAuth = new LdapServiceClient();

 

            List<CountryEntity> lstCountryEntityValue = ldapAuth.GetCountriesForUser(User.Identity.Name);

            List<CountryVM> lstCountryValue = new List<CountryVM>();

            lstCountryValue = AutoMapper.Mapper.Map<List<CountryEntity>, List<CountryVM>>(lstCountryEntityValue);

 

            var model = new CountriesVM

            {

                listCountries = lstCountryValue

            };

            return View(model);

        }

 

         [HttpPost]

        public ActionResult UserCountries(CountriesVM model)

        {

            var selection = model.SelectedCountryId;

            

            if (!ModelState.IsValid)

            {

                return View(model);

            }

 

            return Content("thanks for submitting", "text/plain");

        }

 

Finally the View

@model BC.InterimProductFinder.Portal.ViewModel.CountriesVM

 

@{

    ViewBag.Title = "UserCountries";

}

 

<h2>UserCountries</h2>

@using (Html.BeginForm())

{

    @Html.ValidationMessageFor(x => x.SelectedCountryId)

    foreach (var rec in Model.listCountries)

    {

        <div nowrap="nowrap">

            @Html.RadioButtonFor(x => x.SelectedCountryId, rec.CountryID, new { id = rec.CountryID }) @Html.Label(rec.CountryName)

        </div>

    }

    <input type="submit" value="OK" />

}

 

If you want Question / Answer type approach, here is a link I liked http://www.techiesweb.net/radio-button-list-in-asp-net-mvc/

Tags:

Populate and validate a dropdownlist in asp.net mvc3

by Admin 14. March 2013 09:05

Using ViewBags

in Controller:

public ActionResult CreateCourse()

 {

ViewBag.CourseLevellist = getCourseLevels();

 return View();

   }

in View:

 <div class="editor-field">

            @Html.DropDownList("CourseCategoryId", 

                                    new SelectList(ViewBag.CourseTypeslist as System.Collections.IEnumerable, 

                                    "CourseTypeID", "CourseTypeName"), "Please Select")

            @Html.ValidationMessageFor(model => model.CourseCategoryId)

        </div>

For ViewModel approach Look @ http://stackoverflow.com/questions/4729440/validate-a-dropdownlist-in-asp-net-mvc

Tags:

Date Picker in MVC 3

by Admin 13. March 2013 07:20
@Html.TextBoxFor(model => model.Date, new { id = "date" })
<scripttype="text/javascript">
    $
(document).ready(function(){
        $
("#date").datepicker({ dateFormat:'dd/mm/yy'});
   
});
</script>

the above is using model binding, so i have a date field in my model

and the date chosen from datepicker saves in the date field

hope that helps!

Tags:

The launch of the uk replica watches new timepiece series undoubtedly symbolizes the replica watches history of the brand, and the classic hublot replica watches design explains the mission of the replica watches uk brand's precision watchmaking.

TextBox

Tag cloud

    RecentPosts