Hey Guys I hava a question. I know questions like this are asked often, but I worked on a solution for several hours and read many answers but I couldnt find the right one. I am doing an application using ASP.NET MVC 4 Razor. I´m rather new to this system. I created a .edmx Data Model using Entity Framework 5 (Database-First Approach). This is how my auto-generated Context class looks like:
namespace KSM3.Models
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq;
public partial class kontrollsystemEntities : DbContext
{
public kontrollsystemEntities()
: base("name=kontrollsystemEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
[EdmFunction("kontrollsystemEntities", "udf_GetReportsByController")]
public virtual IQueryable<udf_GetReportsByController_Result> udf_GetReportsByController(string controller_account)
{
var controller_accountParameter = controller_account != null ?
new ObjectParameter("controller_account", controller_account) :
new ObjectParameter("controller_account", typeof(string));
return ((IObjectContextAdapter)this).ObjectContext.CreateQuery<udf_GetReportsByController_Result>("[kontrollsystemEntities].[udf_GetReportsByController](#controller_account)", controller_accountParameter);
}
}
}
and my Model class looks like this:
namespace KSM3.Models
{
using System;
public partial class udf_GetReportsByController_Result
{
public int ID { get; set; }
public string ProviderID { get; set; }
public int VertragID { get; set; }
public System.DateTime Leistungszeitraum_von { get; set; }
public System.DateTime Leistungszeitraum_bis { get; set; }
public string ReportklasseID { get; set; }
public int Version { get; set; }
public string Status { get; set; }
}
}
When I now click on "Add Controller" and select my classes, I get the error message:
"Unable to retrieve Metadata for KSM3.Models.udf_GetReportsByController_Result.cs"
Note: I am using Entity Framework to retrieve information from a user-defined function, not from a table! If I try the same procedure with a table, it works!
What do I have to prepare or change in order to make this work?
Thank you for all answers!
I have solved my problem, thanks!
I had to call the udf_GetReportsByController(string controller_account) method in the controller and hand the IQueryable-Result to my view.
My Controller looks like these (Note: Beginner´s mistake)
public class ReportController : Controller
{
private kontrollsystemEntities db = new kontrollsystemEntities();
//
// GET: /Report/
public ActionResult Index()
{
IQueryable<udf_GetReportsByController_Result> result = db.udf_GetReportsByController(User.Identity.Name);
return View(result.ToList());
}
}
}
Related
I've got this task requiring building a parent/child view in html. NOT USING ANY PLUGINS!
I've created a database and a model (H_Table), and a class (Element) in controller for child nodes.
But how do I get this to work together. So, that it retrieves data from the model passes it to the class and returns to view as model. I'm not really sure whether I explaied it right. Ask away.
My Model:
namespace Tree_List.Models
{
using System;
using System.Collections.Generic;
public partial class H_Table
{
public int ID { get; set; }
public string NAME { get; set; }
public Nullable<int> PARENT_ID { get; set; }
}
}
My Controller:
using System.Collections.Generic;
using System.Web.Mvc;
using Tree_List.Models;
namespace Tree_List.Controllers
{
public class ListController : Controller
{
// GET: List
private Models.ListDBEntities1 db_connection = new Models.ListDBEntities1();
public ActionResult Index()
{
var Items = db_connection.H_Table;
return View(Items);
}
}
public partial class Element
{
public int ID { get; set; }
public string NAME { get; set; }
public List<Element> CHILDS { get; set; }
}
}
If I get your question right you want to render this hierarchical data of yours in a view. To do that you have to use Javascript and jQuery to render this data there are tons of ready libraries and open source examples on how to do this like:
https://www.codeproject.com/tips/696985/how-to-create-treeview-in-mvc
https://www.mindstick.com/Articles/1119/using-treeview-in-asp-dot-net-mvc
You can see them and write one yourself like them. Also take a look at more abstracted tool from Telerik.
Hope it helps :)
I am trying to use Oracle ManagedAccess Client driver to user Oracle Database With ASP.NET MVC 5
Here is My Context:
using System.Configuration;
using Domain.Entities;
using Oracle.ManagedDataAccess.Client;
using Oracle.ManagedDataAccess.EntityFramework;
using System.Collections.Specialized;
namespace Domain.Data
{
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
public partial class SptsOracleDbContext : DbContext
{
public SptsOracleDbContext()
: base(new OracleConnection(ConfigurationManager.ConnectionStrings["SptsOracleDbContext"].ConnectionString), true)
{
}
public DbSet<BranchType> BranchTypes { get; set; }
public DbSet<Branch> Branches { get; set; }
public DbSet<StaffStatu> StaffStatus { get; set; }
public DbSet<ManagerialTitle> ManagerialTitles { get; set; }
public DbSet<AcademicTitle> AcademicTitles { get; set; }
public DbSet<Hospital> Hospitals { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.HasDefaultSchema("SPTS");
modelBuilder.Ignore<Hospital>();
}
}
}
When I try to migrate with update-database command from Package Manager Console It gives me this error:
ORA-00955 name is already used by an existing object
When I check if a table is already created,but there is no created table.
How can I Solve This issue?
Many Thanks For Helps
It looks like there is another object by the same name. You can check it using this query:
select *
from user_objects
where object_name = 'yourObject'
and then you can drop it.
Scenario: Intranet app. Windows authentication. EF 6.1.3. Databases: SQL Server Compact Edition and MS Access. VS Studio 2013.
The solution has 3 projects:
EnqueteWeb.UI - ASP.NET web application;
EnqueteWeb.Dominio - class library for the application domain;
ControleDeAcessoGeral - class library to get data of the user logged from Active Directory, and include/update/delete/list some users that perform some special actions on the app.
As the access control to the app is based on a SQL Server Compact Edition database, I have EntityFramework installed in ControleDeAcessoGeral. I want to have all the methods regarding to users in a class in this project. And so I did it.
This ControleDeAcessoGeral project is defined like this:
Aplicacao
- Corp.cs (methods to deal with Active Directory stuff)
- UsuariosApp.cs (methods to deal with the SQL Server CE database)
Contexto
- DBControleDeAcesso.cs (defines the context)
- InicializaControleDeAcesso.cs (fill in initial data to the
DBControleDeAcesso database)
Entidades
- Perfil.cs (profiles that a user can have on the app)
- Usuarios.cs (users that may perform some actions on the app)
- UsuarioAD.cs (Active Directory user and its data)
The DBControleDeAcesso.cs class has the following code:
using ControleDeAcessoGeral.Models.Entidades;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace ControleDeAcessoGeral.Models.Contexto
{
public class DBControleDeAcesso : DbContext
{
public DBControleDeAcesso() : base("ControleDeAcessoContext") { }
public DbSet<Perfil> Perfis { get; set; }
public DbSet<Usuario> Usuarios { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
The entities classes are the following:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace ControleDeAcessoGeral.Models.Entidades
{
public class Usuario
{
[Key]
public string Logon { get; set; }
public string Nome { get; set; }
[Display(Name="Órgão")]
public string Orgao { get; set; }
public string Email { get; set; }
[StringLength(maximumLength: 4)]
public string Depto { get; set; }
[Display(Name = "Perfis")]
public virtual List<Perfil> Perfis { get; set; }
public Usuario()
{
this.Perfis = new List<Perfil>();
}
}
}
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace ControleDeAcessoGeral.Models.Entidades
{
public class Perfil
{
[Key]
public int Id { get; set; }
[Required(ErrorMessage = "Por favor, informe o NOME DO perfil.")]
[StringLength(maximumLength: 25)]
public string Nome { get; set; }
[StringLength(maximumLength: 255)]
[Display(Name = "Descrição")]
public string Descricao { get; set; }
public virtual List<Usuario> Usuarios { get; set; }
public Perfil()
{
this.Usuarios = new List<Usuario>();
}
}
}
And the UsuariosApp.cs class is as bellow (for the sake of brevity, I'll show only the methods that concerns to the issue):
using ControleDeAcessoGeral.Models.Contexto;
using ControleDeAcessoGeral.Models.Entidades;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
namespace ControleDeAcessoGeral.Models.Aplicacao
{
public class UsuariosApp
{
private DBControleDeAcesso db { get; set; }
public UsuariosApp()
{
db = new DBControleDeAcesso();
}
public void SalvarUsuario(Usuario usuario)
{
db.Usuarios.Add(usuario);
db.SaveChanges();
}
public Perfil LocalizarPerfil(int id)
{
return db.Perfis.Find(id);
}
}
}
The action that tries to save a user (Usuarios.cs) in the SQL Server CE database is in AdministracaoController and has the following code:
using ControleDeAcessoGeral.Models.Aplicacao;
using ControleDeAcessoGeral.Models.Entidades;
using EnqueteWeb.UI.Models;
using EnqueteWeb.UI.ViewModels;
using System.Linq;
using System.Web.Mvc;
namespace EnqueteWeb.UI.Controllers
{
public class AdministracaoController : Controller
{
[HttpPost]
public ActionResult CriarUsuarioNaApp(UsuarioViewModel model)
{
foreach (var item in model.PerfisSelecionados)
{
Perfil perfil = new UsuariosApp().LocalizarPerfil(item);
model.Usuario.Perfis.Add(perfil);
}
if (ModelState.IsValid)
{
new UsuariosApp().SalvarUsuario(model.Usuario);
return RedirectToAction("Usuarios");
}
return View(model);
}
}
}
So, when this action CriarUsuarioNaApp is invoked and the method SalvarUsuario(model.Usuario) runs, the following error occurs:
An entity object cannot be referenced by multiple instances of IEntityChangeTracker
I've read a few about this on web but, unfortunately, I still couldn't make it works.
Hope a wise and good soul will show me the way.
Thanks for your attention.
Paulo Ricardo Ferreira
The problem arises from the fact that you do not dispose of the first DbContext instance (from which you load the profile entities) prior to attaching said entities to the second DbContext instance.
To fix (and some additional suggestions):
have UsuariosApp implement IDisposable and dispose your instance of the DbContext db when disposing UsuariosApp
wrap your newly-disposable UsuariosApp instance in a using statement and use this single instance for both your Perfil loading and Usuario saving logic
optimize Perfil loading by loading all values with single call
validate ModelState.IsValid immediately
Something like this:
public class UsuariosApp : IDisposable
{
private DBControleDeAcesso db { get; set; }
public UsuariosApp()
{
db = new DBControleDeAcesso();
}
public void SalvarUsuario(Usuario usuario)
{
db.Usuarios.Add(usuario);
db.SaveChanges();
}
public Perfil LocalizarPerfil(int id)
{
return db.Perfis.Find(id);
}
public IEnumerable<Perfil> LocalizarPerfiles( IEnumerable<int> ids )
{
return db.Perfils.Where( p => ids.Contains( p.Id ) )
.ToArray();
}
private bool _disposed = false;
protected virtual void Dispose( bool disposing )
{
if( _disposed )
{
return;
}
if( disposing )
{
db.Dispose();
}
_disposed = true;
}
public void Dispose()
{
Dispose( true );
GC.SuppressFinalize( this );
}
}
public ActionResult CriarUsuarioNaApp( UsuarioViewModel model )
{
// validate model state first
if( ModelState.IsValid )
{
// use single, disposable repo/uow instance
using( var uapp = new UsuariosApp() )
{
// get all profiles in a single call, no loop required
var perfils = uapp.LocalizarPerfiles( model.PerfisSelecionados );
model.Usuario.Perfis.AddRange( perfils );
uapp.SalvarUsuario( model.Usuario );
}
return RedirectToAction( "Usuarios" );
}
return View( model );
}
Let me know if that doesn't solve your problem.
I made Entity models in MVC, in model first approach, and I would like to know, how to insert, delete, and modify data.
I try to use
namespace EntityFrameworkModelFirst
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class ModelFirstContainer : DbContext
{
public ModelFirstContainer()
: base("name=ModelFirstContainer")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Department> DepartmentSet { get; set; }
public virtual DbSet<Employee> EmployeeSet { get; set; }
}
using (var context = new ModelFirstContainer())
{
// Perform data access using the context
}
}
But, it makes error to me. The error is: The contextual word 'var' may only appear within a local variable declaration or in script code, and missing ;.
Is it valid now? Where can i do this? Which files?
Thank you
Your using block must be in a method. You can't have it outside of a method. Also, I've removed your OnModelCreating which would have thrown an exception.
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
namespace EntityFrameworkModelFirst
{
public partial class ModelFirstContainer : DbContext
{
public ModelFirstContainer() : base("name=ModelFirstContainer")
{
}
public virtual DbSet<Department> DepartmentSet { get; set; }
public virtual DbSet<Employee> EmployeeSet { get; set; }
}
public class SomeClass
{
public void DoSomeStuff()
{
using (var context = new ModelFirstContainer())
{
// Perform data access using the context
}
}
}
}
A using block is used with IDisposable objects to ensure they get properly disposed. ModelFirstContainer inherits from DbContext which implements IDisposable.
A tutorial on how to work with the Entity Framework DbContext can be found here: Working with DbContext
public class ProductContext : DbContext
{
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
}
using (var context = new ProductContext())
{
// Perform data access using the context
}
im learning ORM in c#. When I`m adding register to Register table the error is displayed.
My classes are.
using System;
using System.Collections.Generic;
using System.Linq;using System.Text;
namespace PreSchool
{
public class Child
{
public int ChildId {get; set;}
public string Name { get; set; }
public string Surname { get; set; }
public virtual List<Register> Registers { get; set; }
public Child()
{
this.Registers = new List<Register>();
}
}
AND
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
namespace PreSchool
{
public class Register //partial
{
public int RegisterId { get; set; }
public DateTime dt_in { get; set; }
public DateTime dt_out { get; set; }
public virtual Child Child { get; set; }
}
}
Function
private void button1_Click(object sender, RoutedEventArgs e)
{
using (var db = new ChildContext())
{
Child bla= ChildrenGrid.SelectedItem as Child ;
var reg = new Register() { dt_in = DateTime.Now, dt_out = DateTime.Now };
bla.Registers.Add(reg);
db.SaveChanges();
}
}
Earlier I had a problem and I had to add "partial" in Register Class to compile the project but now its not necesarry ( why?). The error from subject dipslays in this place : bla.Registers.Add(reg);
Thanks for any help !
It appears as though you are trying to add the Register object to a disposed context. If you are binding records to a grid then they will no longer be attached to the DB when you retrieve them, you need to re-pull the object and update that instead e.g.
using (var db = new ChildContext())
{
// get the id of the selected child
var childId = (ChildrenGrid.SelectedItem as Child).ChildId;
// pull that record from the "live" context
Child entity = db.Child.Single(x => x.ChildId == childId);
// add the new record to the "live" entity
entity.Registers.Add(new Register
{
dt_in = DateTime.Now,
dt_out = DateTime.Now
});
db.SaveChanges();
}
FYI - it's generally a better idea to use view models for your UI rather than actual DB entities.