I'm using ASP.net Entity Framework. So I need to call a stored procedure and want to set a data to DateSet.
This is my function
public DataSet SearchEmployee(string name, string dep)
{
db.f_t_PEOPLE_SearchEmployee(name, dep);
return db.f_t_PEOPLE_SearchEmployee(name, dep);
}
but there is error and it says
Cannot implicitly convert type 'object' to 'System.Data.DataSet'. An explicit conversion exists (are you missing a cast?)
Entity Framework is a ORM. This means that EF maps the data retrieved from BD to classes (objects) wich represents your business entities. I dont know if with some arcane voodoo programming haks you can read a datatable from a SP mapped by EF but what I am sure is that you shouldn't do it. EF was building to avoid DataTables and DataSets.
Related
We are looking for a way of automatically filtering all CRUD operations by a tenant ID in Entity Framework.
The ideas we thought of were:
Using table valued user defined functions
Using stored procedures (but we don't really want to, as we're using an ORM to avoid doing so)
Some how modifying the templates used to generate the SQL to add a where clause on each statement.
Some how modifying the templates used to generate the LINQ in the controllers (we may use MVC).
Any tips?
-thanks
Alex.
Using table valued user defined functions
Table valued function are only available in .NET 4.5 Beta (and not available in code first). Using them will still not help you because you will have to use the function in every LINQ query so it is the same as using where clause.
Using stored procedures (but we don't really want to, as we're using an ORM to avoid doing so)
It can be useful for some special complex queries but generally it is not what you want.
Some how modifying the templates used to generate the SQL to add a where clause on each statement.
Too complex and on completely different level of abstraction.
Some how modifying the templates used to generate the LINQ in the controllers (we may use MVC).
Close to ideal solution. You simply need to wrap access to your entity set into some code which will look like:
public class MultiTenantAccess<T> where T : IMultitenant
{
private IDbSet<T> set;
...
public IQueryable<T> GetQuery(int tenantID)
{
return set.Where(e => e.TenantID == tenantID);
}
}
Sometimes this is core for something called Generic repository but it is really just a wrapper around EF set. You will always use GetQuery to query your data store instead of using DbSet directly.
you may also separate the tenants data into different databases
or into same database, but with different schemas? You can read more about this in an old MSDN article called "Multi-Tenant Data Architecture"
I am trying my hands on MVC 2, ADO.NET EF and POCO. I have generated my entity classes in a separate library using POCO generator.These POCO entities are used as ViewPages (Not sure if that's the right way to design or do I need separate ViewModels classes ?)
Now, if I take case of a simple scenario where I need to add an Employee object( which is related to a Department Master), what then should be the recommended way to transfer these objects between layers.
Layered structure of the application is somewhat like this :
I have thought of various alternatives:
I have a method in the Employee Controller which is named AddEmployee() which accepts the FormCollection as parameter. Within the form collection I get posted data such as Employee Name, Age , Salary etc and the ID of the Selected Department .
1.) One way is that I can create another DTO say EmployeeDepartment DTO which will be used to map values from FormCollection as is. I can then break them at manager layer and use them to create entity objects i.e Employee Object and refer department by query similar to this:
e.Department = Department.where(i => i.deptId == empDepDto.dept_id).first()
I am not a big fan of this and feel that every time there is a relation involved I have to add a DTO and then map it to my entity class.
2.) Second is probably the worst, i.e passing each object as parameter and then couple them in manager layer.
3.) Use POCO as is, Create a Employee Object and Deparment Object at controller layer and pass the POCO object
public void AddEmployee(FormCollection formCollection)
{
Department d = new Deparmtent; d.id = ""; //based on the dropdown value
d.name="" //based on the dropdown selected text;
Employee e = new Employee; e.Name. e. sal....
e.Department = d;
EmployeeManager.AddEmployee(e);
}
But at manager layer I think , I still need to recreate the reference to the Department using LINQ which again is repetitive and doesn't seems to be a clean solution.
Are there better ways of handling this ? Looking for recommendations and best practices.
Firstly, is there any reason you're not using MVC version 3? There's no major breaking changes, so may as well upgrade?
Secondly is there a reason for using FormCollection rather than the strongly typed model-binding? Just change your views to use the strongly typed HTML helpers ( like <%: Html.TextBoxFor(m => m.Property) %>), or make sure the name attributes match the property names, and have your controller receive the type, and model binding will do the rest. There's plenty of tutorials showing this, and articles explaining it. Model binding will work with a name/value collection, like that posted as a form, or against JSON data, or you can find/write custom model binders that work against whatever wacky serialisation protocol you want.
One thing to watch though when passing the actual entity types that Entity Framework will store around, is that you have to be careful when updating existing objects, or with foreign key references to existing objects - all your objects must be attached to the right Entity Framework context. To achieve that you will often see the objects received by the controller having their properties copied to a freshly retrieved entity from a context, either manually or by an object mapper of some kind.
Make a seperate project called "BusinessObjects" or "Model" which contains your POCOs. Then use strongly typed model-binding for MVC and you'll be set.
The method signature will look something like this:
// In your Controller
public void AddEmployee(Employee newObject)
{
YourDataContext dc = new YourDataContext();
dc.Employees.Add(newObject);
dc.SaveChanges();
}
I'm trying EF 4 with POCO's on a small project for the first time. In my Repository implementation, I want to provide a method AddOrUpdate that will add a passed-in POCO to the repository if it's new, else do nothing (as the updated POCO will be saved when SaveChanges is called).
My first thought was to do this:
public void AddOrUpdate(Poco p)
{
if (!Ctx.Pocos.Contains<Poco>(p))
{
Ctx.Pocos.AddObject(p);
}
}
However that results in a NotSupportedException as documented under Referencing Non-Scalar Variables Not Supported (bonus question: why would that not be supported?)
Just removing the Contains part and always calling AddObject results in an InvalidStateException:
An object with the same key already
exists in the ObjectStateManager. The
existing object is in the Unchanged
state. An object can only be added to
the ObjectStateManager again if it is
in the added state.
So clearly EF 4 knows somewhere that this is a duplicate based on the key.
What's a clean, efficient way for the Repository to update Pocos for either a new or pre-existing object when AddOrUpdate is called so that the subsequent call to SaveChanges() will do the right thing?
I did consider carrying an isNew flag on the object itself, but I'm trying to take persistence ignorance as far as practical.
Try to look at ObjectStateManager.TryGetObjectStateEntry Method, it is good described in this stackoverflow queston.
I developed and entity framework (.edmx) application in 4.0 in that i got all the data of my querying table and its foreign key referenced tables data also. but when i change my project to 3.5 i am unable to get the data of foreign key referenced tables data. Please help me out...
In EF4 lazy loading is included and is on by default.
No such luck in prior versions: You may need to add an .Include() to fetch the other data automatically (eager loading) or call Load() on the references to load them (manually).
If the reference table was say "Details" you would do ...
var featuredOffers = context.Hosters_FeaturedOffer.Include("Details").ToList();
See http://msdn.microsoft.com/en-us/library/bb896272.aspx
BTW: Do a search for "strongly typed Include" too - there are some extension methods people have written to remove the magic string and replace it with a compile time checked lambda expression.
For the future answers if you are using newer version of EF;
var o = db.Order.Include(i => i.User).Include(i => i.OrderItem).FirstOrDefault(x=>x.OrderId == orderId);
Trying to do an insert, I have:
jdbcTemplate.update("insert into....", new Object[]{foo.getId(), foo.getName()})
foo.getId() returns a long, and getName() a String.
I have "NUMBER" as the id type in Oracle, and varchar2 for the name field.
I'm getting SQLtype unknown problem.
the update method has a version where I do not have to put in the SQL types, but do I have to, and if so, how?
I'm assuming you mean the Spring Framework JdbcTemplate class. The JdbcTemplate methods will attempt to guess the java.sql.Type for value references, but apparently isn't guessing correctly in this case.
There are a couple of ways to include the type:
The JdbcTemplate.update(String, Object[]) [javadoc](http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/jdbc/core/JdbcTemplate.html#update(java.lang.String, java.lang.Object[])) indicates that you can pass SqlParameterValue instances, consisting of the java.sql.Type and a value.
Alternatively, you can use JdbcTemplate.update(String, Object[], int[]) passing an array of java.sql.Type