Friday, 29 April 2016

using partial view in mvc

No comments
first create controller

example we have edit customer in controller so we will render partial view to edit customer info


controller - 

  public ActionResult EditAddressBook(int addressBookId)
        {
            UnitOfWork uom = new UnitOfWork();
            var addressBookRepository = uom.Repository<AddressBookRepository>();
            var addressResult = addressBookRepository.EditAddressBook(addressBookId);
            AutoMapper.Mapper.CreateMap<AddressBook, AddressBookModel>();
            AddressBookModel model = new AddressBookModel();
            model = AutoMapper.Mapper.Map<AddressBookModel>(addressResult);
            BindDropDownListAddressBook(model);
            return PartialView("_NewCustomer", model);
        }


partial view -



@using (Html.BeginForm("AddCustomer", "Shipment", FormMethod.Post, new { id = "frmAddCustomer", @class = "form-horizontal" }))
{
    <div class="box-body">


        <div class="form-group">

            <div class="col-md-4">
                <label>I.D<span class="text-red ">*</span></label>
                @Html.HiddenFor(x => x.AddressbookId, new { @id = "hdnAddressId" })
                @Html.TextBoxFor(m => m.OrderId, new { @class = "form-control  required", @data = "I.D", maxlength = 50 })
            </div>
            <div class="col-md-4">
                <label>Company Name<span class="text-red ">*</span></label>
                @Html.TextBoxFor(m => m.CompanyName, new { @class = "form-control required", @data = "Company Name", maxlength = 150 })
            </div>

            <div class="col-md-4">
                <label>Contact Name<span class="text-red">*</span></label>
                @Html.TextBoxFor(m => m.ContactName, new { @class = "form-control required", @data = "Contact Name", maxlength = 35 })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-4">
                <label>Address Line 1<span class="text-red">*</span></label>
                @Html.TextBoxFor(m => m.Address1, new { @class = "form-control  required", @data = "Address Line 1", maxlength = 35 })
            </div>
            <div class="col-md-4">

                <label>Addresss Line 2</label>
                @Html.TextBoxFor(m => m.Address2, new { @class = "form-control", maxlength = 35 })
            </div>
            <div class="col-md-4">
                <label>Country<span class="text-red">*</span></label>
                @Html.DropDownListFor(m => m.CountryId, Model.CountryList, "Select Country", new { @class = "form-control  required", @data = "Country" })
            </div>
        </div>


        <div class="form-group">
            <div class="col-md-4">
                <label>Postal/Zipcode<span class="text-red">*</span></label>
                @Html.TextBoxFor(m => m.ZIP, new { @class = "form-control  required", @data = "Zipcode", maxlength = 10, @id = "AddressZip" })
            </div>
            <div class="col-md-4">
                <label>City<span class="text-red">*</span></label>
                @Html.TextBoxFor(m => m.City, new { @class = "form-control required", @data = "City", maxlength = 50 })
            </div>
            <div class="col-md-4">
                <label class="col-sm-2">Province/State<span class="text-red ">*</span></label>
                @Html.DropDownListFor(m => m.StateId, Model.StateList, "Select State", new { @class = "form-control  required", @data = "State" })
                @*@Html.TextBoxFor(m => m.StateId, new { @class = "form-control required", maxlength = 50, @data = "State" })*@
            </div>
        </div>


        <div class="form-group">
            <div class="col-md-4">
                <label class="col-sm-2">Phone<span class="text-red">*</span></label>
                @Html.TextBoxFor(m => m.Phone, new { @class = "form-control required", @data = "Phone" })
            </div>
            <div class="col-md-4">
                <label class="col-sm-2">Email</label>
                @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
            </div>
        </div>
        <div class="clearfix" style="height:20px">&nbsp;</div>  
        <button type="button" id="btnAddContacts" class="btn btn-primary">Submit</button>&nbsp;&nbsp;
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <div class="clearfix" style="height:70px">&nbsp;</div>
    </div>
}



render partial from jquery method - 

 function EditAddressBook(addressBookId) {
                $.ajax({
                    method: "GET",
                    url: '@Url.Action("EditAddressBook", "Shipment")',
                    data: { 'addressBookId': addressBookId },
                    success: function (result) {
                        if (result != undefined && result != null) {
                            $('#modalAddCustomer .modal-body').html('');
                            $('#modalAddCustomer #modalHead').html('Update Cusotomer');
                            $('#modalAddCustomer .modal-body').html(result);
                            $('#modalAddCustomer').modal('toggle');
                            $('#modalAddCustomer').modal('show');
                        }
                        else {

                        }
                    }
                });
            }


modal popup in which result i.e partial view will be - 


<div class="modal fade" id="modalAddCustomer" role="dialog" data-backdrop="static" data-keyboard="false">
        <div class="modal-dialog" style="width: 65%">
            <div class="modal-content">
                <div class="box-header with-border">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title" id="modalHead">Add Customer</h4>
                </div>
                <div class="modal-body">
                </div>
            </div>
        </div>
    </div>

read more

Formating different json and strings with quotation

No comments
valid JSON formate in c# -

with dynamic value - 

 string json = "[{\"message\":\"" + message + "\",\"phoneNumber\":\"" + number + "\"}]";

with static value -

string json = "[{\"message\": \"this is test \", \"phoneNumber\": \"123456\"}]";

read more

Thursday, 28 April 2016

Submitting form and post data dynamically in c#

No comments

here for sudopay api as example to post data instead of using form

from form - 

<form action="http://sandbox.sudopay.com/api/v1/merchants/11/websites/78/vaults/type/cc.json" method="post">
        <input name="user_handle" type="hidden" value="703212898983" />
        <input name="email" type="hidden" value="test@example.com" />
        <input name="credit_card_number" type="hidden" value="4111111111111111" />
        <input name="credit_card_expire" type="hidden" value="10/2016" />
        <input name="credit_card_type" type="hidden" value="visa" />
        <input name="credit_card_name_on_card" type="hidden" value="Fred" />
        <input name="email" type="hidden" value="test@example.com" />
        <input name="address" type="hidden" value="First Street" />
        <input name="city" type="hidden" value="Chennai" />
        <input name="state" type="hidden" value="Tamil Nadu" />
        <input name="country" type="hidden" value="IN" />
        <input name="buyer_ip" type="hidden" value="201.200.01.01" />
        <input name="zip_code" type="hidden" value="38005" />
        <input name="phone" type="hidden" value="9662542112" />
        <input name="success_url" type="hidden" value="https://sudopay.com//?pa=success#sudopay-demo" />
        <input name="cancel_url'" type="hidden" value="https://sudopay.com//?pa=failure#sudopay-demo" />
        <input name="submit" class="btn btn-large" type="submit" value="Pay $1" />
    </form>


instead from c# -

        private static System.Collections.Specialized.NameValueCollection Inputs = new System.Collections.Specialized.NameValueCollection();
 static void Main(string[] args)
        {            
            Inputs.Add("user_handle", "009199199999199");
            Inputs.Add("email", "test@example.com");
            Inputs.Add("credit_card_number", "4111111111111111");
            Inputs.Add("credit_card_expire", "10/2016");
            Inputs.Add("credit_card_type", "visa");
            Inputs.Add("credit_card_name_on_card", "Fred");
            Inputs.Add("email", "test@example.com");
            Inputs.Add("address", "First Street");
            Inputs.Add("city", "Chennai");
            Inputs.Add("state", "Tamil Nadu");
            Inputs.Add("country", "IN");
            Inputs.Add("zip_code", "38005");
            Inputs.Add("phone", "9662542112");
            Inputs.Add("buyer_ip", "201.200.01.01");

            WebClient client = new WebClient();
            client.Headers.Add("Authorization", "Basic MTEzMzc6ZDNkMDhkOGI0YzNlY2NmOGI0ODg3ZDhmN2QxYTc3ZGYxNzY1ZGVkNQ==");
            byte[] response = client.UploadValues("http://sandbox.sudopay.com/api/v1/merchants/11/websites/78/vaults/type/cc.json", Inputs);
            string result = System.Text.Encoding.UTF8.GetString(response);
        }


here authorization key like "MTEzMzc6ZDNkMDhkOGI0YzNlY2NmOGI0ODg3ZDhmN2QxYTc3ZGYxNzY1ZGVkNQ==" can be get from fiddler 
goto tools and textwizard , enter username and password which will return base 64 encoded url use that as authentication


read more

Monday, 25 April 2016

Binding country state city in mvc

No comments
CountryRepository.cs
--------------------------
public class CountryRepository : Repository<Country>
    {
        private DataBaseContext _context = null;
        public CountryRepository(DataBaseContext context, UnitOfWork _uom)
            : base(context, _uom)
        {
            _context = context;
        }

        public List<Country> GetAllCountries()
        {
            return base.GetAll().ToList().OrderBy(x => x.SortCode).ThenBy(y => y.CountryName).ToList();
            //.OrderBy(x => new { x.SortCode }).ThenBy(y => y.CountryName)
        }

        public string GetCountryCode(int countryId)
        {
            return base.GetAll(x => x.CountryId == countryId).Select(x => x.CountryCode).ToString();
        }

        public string GetCountryName(int countryId)
        {
            return base.Get(x => x.CountryId == countryId).CountryName;
        }
    }


StateRepository.cs
-----------------------
 public class StateRepository : Repository<State>
    {
        private DataBaseContext _context = null;
        public StateRepository(DataBaseContext context, UnitOfWork _uom)
            : base(context, _uom)
        {
            _context = context;
        }

        public List<State> GetAllStates(int countryId)
        {
            return base.GetAll(x => x.CountryId == countryId).ToList();
        }

        public List<State> GetStateCode()
        {
            return base.GetAll().ToList();
        }      
    }

HomeController.cs
-------------------------


  public void BindDropDownListShipment(Model model)
        {
            UnitOfWork uow = new UnitOfWork();      
            //Bind Country For From Address
            model.CountryList = GenericSelectListItems.Instance.GetAllCountries();
            //Bind State For From Address                            
            model.StateList = GenericSelectListItems.Instance.GetAllStates(model.CountryId);          
        }

View
------------
    <div class="form-group">
  <label>Country<span class="text-red">*</span></label>
  @Html.DropDownListFor(m => m.CountryId, Model.CountryList, "Select Country", new { @class = "form-control  required", @data = "Country" })
  </div>
  </div>                                    
  <div class="col-md-4">
  <div class="form-group">
  <label>State<span class="text-red">*</span></label>
  @Html.DropDownListFor(m => m.StateId, Model.StateList, "Select State", new { @class = "form-control" })
 </div>
 </div>


 //Add new option
            function AddNewOptionToStateDropdown(id) {
                var newOption1 = $('<option selected="selected">');
                newOption1.attr('value', 0).text("Select State");
                $('#' + id).append(newOption1);
            }


//Get states from country
                $('#CountryId').change(function () {
                    $('#StateId').empty();
                    AddNewOptionToStateDropdown('StateId');

                    if (isNaN(parseInt($(this).val()))) {
                        return;
                    }
                        var CountryList = $('#CountryId :selected').text();
                        $('#StateId').css('pointer-events', 'auto');
                        $.ajax({
                            method: "GET",
                            url: "@Url.Action("GetStateByCountryAndZip", "Home")",
                            data: { 'CountryName': CountryList },
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function (result) {
                                if (result != undefined && result != null) {
                                    $('#City').empty();
                                    $('#City').val(result["City"]);
                                    var newOption1 = $('<option selected="selected">');
                                    newOption1.attr('value', result["State"]).text(result["State"]);
                                    $('#StateId').append(newOption1);
                                }
                            },
                            failure: function () {
                            }
                        });
                    }
                });



read more

Sending Json Data to Controller and return json data

No comments
View
---------

$('#Client').click(function () {
               $.ajax({
                            method: "GET",
                            url: "@Url.Action("GetClients", "Home")",
                            data: { 'Name': 'Vikas', 'Code': '4049' },
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function (result) {
                                if (result != undefined && result != null) {
                                  alert('ok');
                                }
                                else {
                                  alert('not found');
                                }
                            },
                            failure: function () {
                               alert('error');
                            }
                        });
               });



controller.cs
------------------

 public string GetClients(string Name, string Code)
        {          
            UnitOfWork uow = new UnitOfWork();
            var postalData = uow.Repository<GetClientRepository>();
            var result = postalData.GetClient(Name, Code).FirstOrDefault();
            return Newtonsoft.Json.JsonConvert.SerializeObject(result);
        }
read more

Email Factory to use email sending in background

No comments
GenericListAppconfig.cs
---------------------------------
public class GenericListAppconfig
    {
        private static GenericListAppconfig _GenericListAppconfig = new GenericListAppconfig();
        UnitOfWork uom = new UnitOfWork();
        private GenericListAppconfig()
        {

        }

        public static GenericListAppconfig intance
        {
            get{
                return _GenericListAppconfig;
            }
        }

        public List<AppConfig> GetAppConfigData(string groupName)
        {
            var appConfigData = uom.Repository<AppconfigRepository>();
            var appConfigList = appConfigData.GetAllAppConfig(groupName);
            return appConfigList.ToList();
        }      
    }
 


EmailNotification.cs
------------------------------
 public void SendMail(string toEmail, string subject,string fromEmail, string body,string attachmentFile)
        {
            MailMessage mail = new MailMessage();
            var appDataList = GenericListAppconfig.intance.GetAppConfigData("smtp");
            SmtpClient smtpServer = new SmtpClient(appDataList.FirstOrDefault(x => x.name == "smtp.host").Value);
            smtpServer.UseDefaultCredentials = true;          
            smtpServer.Credentials = new System.Net.NetworkCredential(appDataList.FirstOrDefault(x => x.name == "smtp.username").Value, appDataList.FirstOrDefault(x =>                                                                             x.name == "smtp.password").Value);

            if (!string.IsNullOrEmpty(attachmentFile))
            {
                System.Net.Mail.Attachment attachment;
                attachment = new System.Net.Mail.Attachment(attachmentFile);
                mail.Attachments.Add(attachment);
            }

            smtpServer.Port = Convert.ToInt32(appDataList.FirstOrDefault(x => x.name == "smtp.port").Value);        
            smtpServer.EnableSsl = true;
         
            mail.From = new MailAddress(fromEmail);
            mail.IsBodyHtml = true;
            mail.To.Add(toEmail);
            mail.Subject = subject;
            mail.Body = body;
            mail.Priority = MailPriority.High;
            Task.Factory.StartNew(() => smtpServer.Send(mail), TaskCreationOptions.LongRunning);
         
        }


using EmailNotification in controller
----------------------------------------------

 string filePath = Server.MapPath("~/" + Express.Web.Models.GenericListAppconfig.intance.GetAppConfigData("Client").FirstOrDefault(x => x.name == "Client.path").Value + "/" + id + "/" + id + ".pdf");

            EmailNotification EmailNotification = new Utils.EmailNotification();
            var appDataList = GenericListAppconfig.intance.GetAppConfigData("smtp");
            EmailNotification.SendMail(email, "Shipment Details", appDataList.FirstOrDefault(x => x.name == "smtp.noreply").Value, htmlBody.ToString(), filePath);

read more

Creating Factory To Use Property Of Class Everywhere - SessionFactory

No comments
SessionFactory.CS -

 public class SessionFactory
    {
        private static SessionFactory _SessionFactory = new SessionFactory();
        private SessionFactory()
        {

        }
        public static SessionFactory Instance
        {
            get
            {
                return _SessionFactory;
            }
        }

      public Customer CurrentCustomer
        {
            get
            {
                if (HttpContext.Current.Session["user"] == null)
                {                  
                    return null;
                }
                return (Customer)HttpContext.Current.Session["user"];
            }
            set
            {
                HttpContext.Current.Session["user"] = value;
            }
        }
}


using SessionFactory.CS in controller
------------------------------------------------
 UnitOfWork uom = new UnitOfWork();
 uom.BeginTransaction();
 var updateCustomer = uom.Repository<SignUpRepository>();
 var resultCustomer = updateCustomer.Get(x => x.CustomerId ==  SessionFactory.Instance.CurrentCustomer.CustomerId);
 resultCustomer.CreditLimit = SessionFactory.Instance.CurrentCustomer.CreditLimit;
 updateCustomer.UpdateCustomer(resultCustomer);
 uom.Commit();

read more

MVC Repository Pattern With EntityFramwork- Getting Started

No comments

first we will create 3 projects in one solution for starting up our project

1. Test.Web - which contains our mvc project (MVC Project)
2. Repository.Pattern - which contains repository pattern
3. Test.Entities - which contains classes of database table


prerequisite - add entity framework from

1.Test.Web
------------------

create MVC project and create controller and view

HomeController.cs  -

 public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
  }


2. Repository.Pattern - 
------------------------------

add DataBaseContext.cs , unitofwork.cs for DbContext

DataBaseContext.cs -

  public class DataBaseContext : DbContext
    {
        private DbSet<Customer> Registration { get; set; }  

        public DataBaseContext()
            : base("Name=ConnectionString")
        {
            Configuration.LazyLoadingEnabled = false;
            Configuration.ProxyCreationEnabled = false;
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
        }
    }

Unitofwork.cs - 

public class UnitOfWork : IDisposable
    {
        #region Declaration
        private DataBaseContext entities = null;
        private DbContextTransaction _transaction;
        #endregion

        #region Ctor
        public UnitOfWork()
        {
            //entities = new DBContext(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
            entities = new DataBaseContext();

        }
        #endregion

        #region Create Repository Instance
        public T Repository<T>() where T : class
        {
            Object[] args = { entities, this };

            var repository = Activator.CreateInstance(typeof(T), args);
            return (T)repository;
        }

        private Dictionary<Type, object> repositories = new Dictionary<Type, object>();
        public IRepository<T> RepositoryInstance<T>() where T : class
        {
            if (repositories.Keys.Contains(typeof(T)) == true)
            {
                return repositories[typeof(T)] as IRepository<T>;
            }
            IRepository<T> repo = new Repository<T>(entities, this);
            repositories.Add(typeof(T), repo);
            return repo;
        }

        #endregion

        #region DB Transactions
        public void BeginTransaction()
        {
            _transaction = entities.Database.BeginTransaction();
        }
        public bool Commit()
        {
            _transaction.Commit();
            return true;
        }
        public void Rollback()
        {
            _transaction.Rollback();
        }
        public void SaveChanges()
        {
            entities.SaveChanges();
        }
        #endregion

        #region Dispose
        private bool disposed = false;
        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    entities.Dispose();
                }
            }
            this.disposed = true;
        }
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        #endregion
    }

IRepository.cs -

 public interface IRepository<T> where T : class
    {
        IEnumerable<T> GetAll(Func<T, bool> predicate = null);
        T Get(Func<T, bool> predicate);
        void Add(T entity);
        void AddRange(List<T> entity);
        void Attach(T entity);
        void Update(T entity);
        void Delete(T entity);
        void DeleteRange(List<T> entity);
        IEnumerable<T> ExecWithStoreProcedure(string query, params object[] parameters);
        //T FindSingleBy<T>(Expression<Func<T, bool>> predicate);
        //IQueryable<T> FindAllBy<T>(Expression<Func<T, bool>> predicate);
        //IQueryable<T> FindBy<T, TKey>(Expression<Func<T, bool>> predicate, Expression<Func<T, TKey>> orderBy);

    }


Repository.cs - 


  public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
    {
        private DataBaseContext _context = null;
        private readonly DbSet<TEntity> _dbSet;
        UnitOfWork uom = null;
        public Repository(DataBaseContext context, UnitOfWork _uom)
        {
            _context = context;
            uom = _uom;
            var dbContext = context as DbContext;

            if (dbContext != null)
            {
                _dbSet = dbContext.Set<TEntity>();
            }
        }
        public IEnumerable<TEntity> GetAll(Func<TEntity, bool> predicate = null)
        {
            if (predicate != null)
            {
                return _dbSet.Where(predicate);
            }

            return _dbSet.AsEnumerable();
        }
        public TEntity FindSingleBy<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : class
        {
            if (predicate != null)
            {
                using (_context = new DataBaseContext())
                {
                    return _context.Set<TEntity>().Where(predicate).SingleOrDefault();
                }
            }
            else
            {
                throw new ArgumentNullException("Predicate value must be passed to FindSingleBy<T>.");
            }
        }

        public virtual IQueryable<TEntity> FindAllBy<TEntity>(Expression<Func<TEntity, bool>> predicate, DataBaseContext _context) where TEntity : class
        {
            if (predicate != null)
            {
                return _context.Set<TEntity>().Where(predicate);
            }
            else
            {
                throw new ArgumentNullException("Predicate value must be passed to FindAllBy<T>.");
            }
        }

        public IQueryable<TEntity> FindBy<TEntity, TKey>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, TKey>> orderBy) where TEntity : class
        {
            if (predicate != null)
            {
                if (orderBy != null)
                {
                    using (_context = new DataBaseContext())
                    {
                        return FindAllBy<TEntity>(predicate, _context).OrderBy(orderBy).AsQueryable<TEntity>(); ;
                    }
                }
                else
                {
                    throw new ArgumentNullException("OrderBy value must be passed to FindBy<T,TKey>.");
                }
            }
            else
            {
                throw new ArgumentNullException("Predicate value must be passed to FindBy<T,TKey>.");
            }
        }

        public TEntity Get(Func<TEntity, bool> predicate)
        {
            return _dbSet.FirstOrDefault(predicate);
        }

        public void Add(TEntity entity)
        {
            _dbSet.Add(entity);
            uom.SaveChanges();
        }

        public void AddRange(List<TEntity> entity)
        {
            _dbSet.AddRange(entity);
            uom.SaveChanges();
        }

        public void Update(TEntity entityToUpdate)
        {
            var entry = _context.Entry(entityToUpdate);
            var key = this.GetPrimaryKey(entry);

            if (entry.State == EntityState.Detached)
            {
                var currentEntry = _dbSet.Find(key);
                if (currentEntry != null)
                {
                    var attachedEntry = _context.Entry(currentEntry);
                    attachedEntry.CurrentValues.SetValues(entityToUpdate);
                }
                else
                {
                    _dbSet.Attach(entityToUpdate);
                    entry.State = EntityState.Modified;
                }
            }
        }

        private int GetPrimaryKey(DbEntityEntry entry)
        {
            var myObject = entry.Entity;
            var property =
                myObject.GetType()
                    .GetProperties()
                    .FirstOrDefault(prop => Attribute.IsDefined(prop, typeof(KeyAttribute)));
            return (int)property.GetValue(myObject, null);
        }

        public void Attach(TEntity entity)
        {
            _dbSet.Attach(entity);
            _context.Entry(entity).State = EntityState.Modified;
            uom.SaveChanges();
        }

        public void Delete(TEntity entity)
        {
            _context.Entry(entity).State = EntityState.Deleted;
            _dbSet.Remove(entity);
            uom.SaveChanges();
        }
        public void DeleteRange(List<TEntity> entity)
        {
            _dbSet.RemoveRange(entity);
            uom.SaveChanges();
        }
        public IEnumerable<TEntity> ExecWithStoreProcedure(string query, params object[] parameters)
        {
            return _context.Database.SqlQuery<TEntity>(query, parameters);
        }

    }


Create Customer repository noe

ContactsRepository.cs


 public class ContactsRepository: Repository<Contacts>
    {
        private DataBaseContext _context = null;
        public ContactsRepository(DataBaseContext context, UnitOfWork _uom)
            : base(context, _uom)
        {
            _context = context;
        }
        public void AddContacts(Contacts Contacts)
        {
            var dbset = _context.Set<Contacts>();
            dbset.Add(Contacts);
            _context.SaveChanges();
        }
     

        public Contacts GetContactsById(int contactId)
        {
            var dbset = _context.Set<Contacts>();
            var contacts = dbset.FirstOrDefault(x => x.ContactsId == contactId);
            if (contacts != null)
            {
                return contacts;
            }
            return null;

        }


    }


3.Test.Entities
--------------------


   public class Contacts
    {
        [Key]
        public int ContactsId { get; set; }
        public int CustomerId { get; set; }
        [Required]
        [StringLength(35)]
        public string Address1 { get; set; }
        [StringLength(35)]
        public string Address2 { get; set; }
        [Required]

        public int CountryId { get; set; }
        //[Required]

        public string StateId { get; set; }
        [Required]
        [StringLength(50)]
        public string City { get; set; }
        [Required]
        [StringLength(10)]
        public string ZIP { get; set; }
        [Required]
        [StringLength(15)]
}

using repository in controller--

HomeController.cs  -

 public class HomeController : Controller
    {
        public ActionResult Index()
        {
                 var insertContacts = uom.Repository<ContactsRepository>();
                Contacts contacts = new Contacts();
                contacts.CustomerId = SessionFactory.Instance.CurrentCustomer.CustomerId;
                contacts.Address1 = shipmentModel.ShipFrom.Address1;
                contacts.Address2 = shipmentModel.ShipFrom.Address2;
                contacts.CountryId = shipmentModel.ShipFrom.CountryId;
                contacts.StateId = shipmentModel.ShipFrom.StateId;
                contacts.City = shipmentModel.ShipFrom.City;
                contacts.ZIP = shipmentModel.ShipFrom.ZIP;
                contacts.Phone = shipmentModel.ShipFrom.Phone;              
                insertContacts.AddContacts(contacts);              
                return View();
        }
  }
read more