MVC Database First Failed to set database initializer - asp.net-mvc

I am new to MVC and I have already created Database after we generated the ADO entity data model called HRContextEntities and we created just a bankviewmodel and its Repository and its Index view to display the Database Banks in a List:
Context :
public partial class HRContextEntities : DbContext
{
public HRContextEntities()
: base("name=HRContextEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<ACTIONS> ACTIONS { get; set; }
public virtual DbSet<BANKS> BANKS { get; set; }
public virtual DbSet<EMP_ALAWA> EMP_ALAWA { get; set; }
public virtual DbSet<EMP_CARDS> EMP_CARDS { get; set; }
public virtual DbSet<EMP_DAORA> EMP_DAORA { get; set; }
public virtual DbSet<EMP_DEGREES> EMP_DEGREES { get; set; }
public virtual DbSet<EMP_DEGREES_WORKERS> EMP_DEGREES_WORKERS { get; set; }
public virtual DbSet<EMP_DISSENT> EMP_DISSENT { get; set; }
public virtual DbSet<EMP_EMPLOYEES> EMP_EMPLOYEES { get; set; }
public virtual DbSet<EMP_ENDEMP> EMP_ENDEMP { get; set; }
public virtual DbSet<EMP_ENTEDAB> EMP_ENTEDAB { get; set; }
public virtual DbSet<EMP_EQRAR> EMP_EQRAR { get; set; }
public virtual DbSet<EMP_HASMIAT> EMP_HASMIAT { get; set; }
public virtual DbSet<EMP_HOLIDAYS> EMP_HOLIDAYS { get; set; }
public virtual DbSet<EMP_JOBS> EMP_JOBS { get; set; }
...............................
Bank View Model :
public class BankViewModel
{
public decimal BankID { get; set; }
public string BankName { get; set; }
public string BankSymbol { get; set; }
}
Bank Repository class:
public class BankRepository
{
HRContextEntities db = new HRContextEntities();
public BankViewModel[] GetAll(int? take, int? skip)
{
return db.BANKS.Select(s => new BankViewModel { BankID = s.ID, BankName = s.NAME })
.OrderBy(s => s.BankID).Skip(skip != null ? skip.Value : 0)
.Take(take != null ? take.Value : int.MaxValue).ToArray();
}
}
_Banks Partial View from:
#model IEnumerable<HumanResourceManagement.Models.BankViewModel>
#foreach (var item in Model)
{
<tr class="odd gradeX">
<td>
#item.BankID
</td>
<td>
#item.BankName
</td>
<td>
RYD
</td>
</tr>
}
Exception:
Additional information: Failed to set database initializer of type 'MyProject.Context.Config.ContextInitializer, MyProject.Context' for DbContext type 'App.Context.Default, App.Context' specified in the application configuration. See inner exception for details.
web.config
<contexts>
<context type="App.Context.Default, App.Context">
<databaseInitializer type="MyProject.Context.Config.ContextInitializer, MyProject.Context" />
<!--<databaseInitializer type="MyProject.Context.Config.ContextInitializer, MyProject.Context" />-->
</context>
</contexts>
so what is the solution for this exception

I think your problem lies in your web.config file:
<contexts>
<context type="App.Context.Default, App.Context">
<databaseInitializer type="MyProject.Context.Config.ContextInitializer, MyProject.Context" />
</context>
</contexts>
The context type specifies the fully qualified context class name and the assembly it's in, and the databaseinitializer type specifies the fully qualified name of the initializer class and the assembly it's in. Read this for more info.
Basically, the second param for context type AND databaseinitializer should be the project assembly, not the context. So it should follow this pattern:
<context type=" Blogging.BlogContext, MyAssembly">
<databaseInitializer type="Blogging.MyCustomBlogInitializer, MyAssembly" />
</context>
So in your code, try this (I think your assembly is MyProject):
<contexts>
<context type="MyProject.App.Context, MyProject">
<databaseInitializer type="MyProject.Context.Config.ContextInitializer, MyProject" />
</context>
</contexts>

Related

why wont my asp.net mvc application seed work properly?

I have the following code to create entities and seed them with data for use in an asp.net mvc application. I am using code first and entity framework. I generate controllers and run the application but on the index.cshtml page my list is empty where the seed data should be.
public class MyContext : DbContext
{
public MyContext() : base("dataDb") {}
public DbSet<Owner> Owners { get; set; }
public DbSet<Pet> Pets { get; set; }
}
public class MyInitializer : DropCreateDatabaseAlways<MyContext>
{
protected override void Seed(MyContext context)
{
// seed database here
context.Owners.AddOrUpdate(
new Owner()
{
//name=,
//id=,
Pets = new List<Pet> { new Pet()
{
//id=,
//name=,
},
new Pet()
{
//id=,
//name=,
}}
},
new Owner()
{
//id=,
//name=,
Pets = new List<Pet> { new Pet()
{
//id=,
//name=,,
}
}
}
);
context.SaveChanges();
}
}
public class Owner
{
public int OwnerId { get; set; }
public string Name { get; set; }
public virtual List<Pet> Pets { get; set; }
}
public class Pet
{
public int PetId { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public virtual Owner Owner { get; set; }
}
}
I found a solution to this problem:
Database.SetInitializer(new MyInitializer()); //important for seed to work
add this line to the context constuctor:
public MyContext() : base("dataDb") {}
You can also add it to your web.config. When it comes to deployment, you can easily remove it from the web.config by using configuration transformer.
<entityFramework>
<contexts>
<context type="MyProject.MyContext, MyProject">
<databaseInitializer type="MyProject.MyInitializer, MyProject" />
</context>
</contexts>
...
</entityFramework>
<connectionStrings>
<add name="MyContext" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=OwnersPets; AttachDBFilename=|DataDirectory|\OwnersPets.mdf; Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionString>
Example conn string to use with localDb

object reference not set to an instance of an object scaffolding mvc

I have a problem to scaffolding my model.
I get following error "object reference not set to an instance of an object"
My model :
public class Position
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long PositionID { get; set; }
public long OfferID { get; set; }
[Required]
[Display(Name = "Positie omschrijving")]
public string Name { get; set; }
[Required]
public int PositionNr { get; set; }
[Required]
public double WorkingHeight { get; set; }
public long PalletTypeID { get; set; }
public long MotorTypeID { get; set; }
public long Enveriment { get; set; }
}
My DBContext :
public class FlowContext : DbContext
{
public DbSet<Position> Positions { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
this.Configuration.LazyLoadingEnabled = true;
//Positie
modelBuilder.Entity<Position>()
.HasKey(j => j.PositionID);
}
}
My connection string in web.config
<connectionStrings>
<add name="FlowContext" connectionString="data source=.\SqlExpress; Integrated Security=True;Initial Catalog=Flow;" providerName="System.Data.SqlClient" />

Retrieve data from sql in MVC 4

Platfrom : MVC4
Hi,
I am new to MVC4 and I am trying to retrieve the data from SQL using Entity framework, but it fails. Here is the code I have tried so far :
Model: MovieListing.cs
[Table("MovieMaster")]
public class MoviesListing
{
public int MovieId { get; set; }
public string Name { get; set; }
public string year { get; set; }
public string Image { get; set; }
public string producer { get; set; }
public string plot { get; set; }
}
Model:
public class MovieContext:DbContext
{
public DbSet<MoviesListing> Movies { get; set; }
}
View :
#model MovieManiac.Models.MoviesListing
#{
ViewBag.Title = "Moviedetails";
}
<h2>Moviedetails</h2>
<table>
<tr>
<td>Movie Name</td>
<td> #Model.Moviename</td>
</tr>
</table>
Controller:
public ActionResult MovieDetails(int id)
{
MovieContext objMovies = new MovieContext();
MoviesListing movie = objMovies.Movies.Single(mov => mov.MovieId == id);
return View(movie);
}
So, in the browser, when I enter the Id, I want to retrieve information from database.I am using local sql db. Any suggestions?
Connection String:
</configSections>
<connectionStrings>
<add name="MovieContext" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-MovieManiac-20150318225934;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-MovieManiac-20150318225934.mdf" />
</connectionStrings>
error:
An exception of type 'System.Data.Entity.ModelConfiguration.ModelValidationException' occurred in EntityFramework.dll but was not handled in user code
Additional information: One or more validation errors were detected during model generation:
\tSystem.Data.Entity.Edm.EdmEntityType: : EntityType 'MoviesListing' has no key defined. Define the key for this EntityType.
\tSystem.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet 'Movies' is based on type 'MoviesListing' that has no keys defined.
You need to add the Key attribute to the I'd property so EF knows what is the primary key
https://msdn.microsoft.com/en-us/data/jj591583.aspx
http://www.entityframeworktutorial.net/code-first/key-dataannotations-attribute-in-code-first.aspx
Update
You may be able to use int and numeric, although I wouldn't bother myself, just change your model to decimal to match the datatype mapping... https://msdn.microsoft.com/en-us/library/cc716729(v=vs.110).aspx... if you have a need to use numeric.
Also decorate your class with the Key attribute
[Table("MovieMaster")]
public class MoviesListing
{
[Key]
public int MovieId { get; set; }
public string Name { get; set; }
public string year { get; set; }
public string Image { get; set; }
public string producer { get; set; }
public string plot { get; set; }
}
You can read about using a decimal (numeric) as a key http://dotnetwindow.blogspot.co.uk/2012/06/using-decimal-as-primary-key-in-entity.html
BTW, are you using code first?
add property to your entity
[Table("MovieMaster")]
public class MoviesListing
{
public int Id { get; set; } // add this
public int MovieId { get; set; }
public string Name { get; set; }
public string year { get; set; }
public string Image { get; set; }
public string producer { get; set; }
public string plot { get; set; }
}
or else use this
public class MovieContext:DbContext
{
public DbSet<MoviesListing> Movies { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<MoviesListing>.HasKey(x => x.MovieId );
base.OnModelCreating(modelBuilder);
}
}

WCF Service methods called twice [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have a wcf service with the following web.config in the server.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="myconnection" connectionString="myconnectionstr"/>
</connectionStrings>
<system.serviceModel>
<services>
<service behaviorConfiguration="PSWebServis.PServisBehavior" name="PSWebServis.PServis">
<endpoint address="" binding="wsHttpBinding" contract="PSWebServis.IPServis" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8000/" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="PSWebServis.PServisBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
and this is related part in web.config in client.
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_IPServis" />
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://sunucu:8000/PServis.svc" binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_IPServis" contract="PSWebServis.IPServis"
name="WSHttpBinding_IPServis">
<identity>
<servicePrincipalName value="host/SUNUCU" />
</identity>
</endpoint>
</client>
Here is a part of my interface in the service
[ServiceContract]
public interface IPServis
{
[OperationContract]
string InsertMusteri(MusterilerModel musteri);
}
and related part in service class.
public class PServis : IPServis
{
public string InsertMusteri(MusterilerModel musteri)
{
if (musteri != null)
{
DataTable dtSonuc = new DataTable();
SqlCommand command = new SqlCommand("InsertMusteriModel", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#musteriTablo", musteri.KayitTablosu);
command.Parameters.AddWithValue("#telefonTablo", musteri.TelefonKayit);
command.Parameters.AddWithValue("#adresTablo", musteri.AdresKayit);
connection.Open();
command.ExecuteNonQuery();
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(dtSonuc);
connection.Close();
return dtSonuc.Rows[0]["IslemDurum"].ToString();
}
return "Başarısız";
}
}
My MusterilerModel class:
[DataContract]
public class MusterilerModel
{
[DataMember(Order=0)]
public int MusteriID { set; get; }
[DataMember(Order = 1)]
public string Ad { set; get; }
[DataMember(Order = 2)]
public string Soyad { set; get; }
[DataMember(Order=3)]
public string KullaniciAdi { set; get; }
[DataMember(Order = 4)]
public string Email { set; get; }
[DataMember(Order = 5)]
public DateTime DogumTarihi { set; get; }
[DataMember(Order=6)]
public string GrupAdi { set; get; }
[DataMember(Order=7)]
public int Renk { set; get; }
[DataMember(Order=8)]
public decimal Bakiye { set; get; }
[DataMember(Order=9)]
public string Adres { set; get; }
[DataMember(Order=10)]
public string AdresAciklamasi { set; get; }
[DataMember(Order=11)]
public string Firma { set; get; }
[DataMember(Order=12)]
public string VergiDairesi { set; get; }
[DataMember(Order=13)]
public string VergiNo { set; get; }
[DataMember(Order=14)]
public int BayiID { set; get; }
[DataMember(Order=15)]
public string Il { set; get; }
[DataMember(Order = 16)]
public string Ilce { set; get; }
[DataMember(Order = 17)]
public decimal YemekPara { get; set; }
[DataMember(Order=18)]
public string Sifre { set; get; }
[DataMember(Order=19)]
public int GrupID { set; get; }
[DataMember(Order=20)]
public string BayiAdi { set; get; }
[DataMember(Order=21)]
public int SehirID { set; get; }
[DataMember(Order=22)]
public int IlceID { set; get; }
[DataMember(Order=23)]
public DateTime EvlilikYilDonumu { set; get; }
[DataMember(Order=24)]
public DateTime KayitTarihi { set; get; }
[DataMember(Order=25)]
public string KayitEdenPersonel { set; get; }
[DataMember(Order=26)]
public int KayitEdenPersonelID { set; get; }
[DataMember(Order=27)]
public bool AktifMi { set; get; }
[DataMember(Order=28)]
public string Aciklama { set; get; }
[DataMember(Order=29)]
public string OzelKod { set; get; }
[DataMember(Order=30)]
public int SatisID { set; get; }
[DataMember(Order=31)]
public DataTable KayitTablosu { set; get; }
[DataMember(Order=32)]
public DataTable TelefonKayit { set; get; }
[DataMember(Order=33)]
public DataTable AdresKayit { set; get; }
}
When i try to use InsertMusteri method, there are 2 records in the database. As you see, i put my information into datatable and send it to the service. I checked, if datatable has more than 1 value but that was not the problem. I don't know where is the problem.
Comment this line
command.ExecuteNonQuery();
And check if it's work properly.
I think "Fill" command executs your command.

ASP.NET display related detail records via Razor

I am new to asp.net and c#, I have been trying to duplicate and app done in php using MVC3, generating the code from the same database. I have a question about showing the detail records in my "Details" view.
namespace MvcApplication5.Models
{
[DataContract(IsReference = true)]
[KnownType(typeof(masterDomain))]
[KnownType(typeof(masterFIP))]
[KnownType(typeof(masterSFPF))]
[KnownType(typeof(rgCountiesServed))]
[KnownType(typeof(rgKeyword))]
[KnownType(typeof(rgServicesProvided))]
public partial class rgOrganization
{
public rgOrganization()
{
this.rgCountiesServeds = new HashSet<rgCountiesServed>();
this.rgKeywords = new HashSet<rgKeyword>();
this.rgServicesProvideds = new HashSet<rgServicesProvided>();
}
[DataMember]
public int orgID { get; set; }
[DataMember]
public string ORGANIZATION { get; set; }
[DataMember]
public string CONTACT_PERSON { get; set; }
[DataMember]
public string PHONE_NUMBER { get; set; }
[DataMember]
public string FAX_NUMBER { get; set; }
[DataMember]
public string EMAIL_ADDRESS { get; set; }
[DataMember]
public string WEBSITE { get; set; }
[DataMember]
public string STREET_1 { get; set; }
[DataMember]
public string STREET_2 { get; set; }
[DataMember]
public string CITY { get; set; }
[DataMember]
public string ZIP_CODE { get; set; }
[DataMember]
public string COUNTY { get; set; }
[DataMember]
public string FIPS { get; set; }
[DataMember]
public string MAILING_ADDRESS { get; set; }
[DataMember]
public Nullable<int> SFPF { get; set; }
[DataMember]
public Nullable<int> DOMAIN { get; set; }
[DataMember]
public virtual masterDomain masterDomain { get; set; }
[DataMember]
public virtual masterFIP masterFIP { get; set; }
[DataMember]
public virtual masterSFPF masterSFPF { get; set; }
[DataMember]
public virtual ICollection<rgCountiesServed> rgCountiesServeds { get; set; }
[DataMember]
public virtual ICollection<rgKeyword> rgKeywords { get; set; }
[DataMember]
public virtual ICollection<rgServicesProvided> rgServicesProvideds { get; set; }
}
View Code
#model MvcApplication5.Models.rgOrganization
#{
ViewBag.Title = #Html.DisplayFor(model => model.ORGANIZATION);
}
#section Scripts {
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false"></script>
}
<h2>#Html.DisplayFor(model => model.ORGANIZATION)</h2>
<h3><span id="mailing_address">
#Html.DisplayFor(model => model.MAILING_ADDRESS)
</span></h3>
<fieldset>
<legend> #Html.DisplayFor(model => model.COUNTY) COUNTY</legend>
<div class="display-field">
<strong>#Html.DisplayFor(model => model.ORGANIZATION)</strong>
</div>
<div class="display-field">
#Html.DisplayFor(model => model.CONTACT_PERSON)
</div>
<!-- would like to display services provided here -->
</fieldset>
My question is how do I access the 'rgCountiesServeds'and 'rgServicesProvideds' via Razor?
They appear to be members of your model.
So you can access the collection as
model.rgServicesProvided
To iterate through the collection, do something like this:
#foreach (var serv in model.ServicesProvided) {
Service is #serv.ToString()<br/>
}
Replace serv.ToString() with whatever property you want to display.
If I understand what you're asking, you can access the rgCountiedServeds and rgServicesProvideds just like the other properties of rgOrganization. They are collections and properties of your model so you can loop over them in the View or create a drop down list for each of those properties. I.e.,
#Html.DropDownList("DropDownCounties", Model.rgCountiesServeds)

Resources