Search Results

Search found 49963 results on 1999 pages for 'entity system'.

Page 12/1999 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • GuestPost: Unit Testing Entity Framework (v1) Dependent Code using TypeMock Isolator

    - by Eric Nelson
    Time for another guest post (check out others in the series), this time bringing together the world of mocking with the world of Entity Framework. A big thanks to Moses for agreeing to do this. Unit Testing Entity Framework Dependent Code using TypeMock Isolator by Muhammad Mosa Introduction Unit testing data access code in my opinion is a challenging thing. Let us consider unit tests and integration tests. In integration tests you are allowed to have environmental dependencies such as a physical database connection to insert, update, delete or retrieve your data. However when performing unit tests it is often much more efficient and productive to remove environmental dependencies. Instead you will need to fake these dependencies. Faking a database (also known as mocking) can be relatively straight forward but the version of Entity Framework released with .Net 3.5 SP1 has a number of implementation specifics which actually makes faking the existence of a database quite difficult. Faking Entity Framework As mentioned earlier, to effectively unit test you will need to fake/simulate Entity Framework calls to the database. There are many free open source mocking frameworks that can help you achieve this but it will require additional effort to overcome & workaround a number of limitations in those frameworks. Examples of these limitations include: Not able to fake calls to non virtual methods Not able to fake sealed classes Not able to fake LINQ to Entities queries (replace database calls with in-memory collection calls) There is a mocking framework which is flexible enough to handle limitations such as those above. The commercially available TypeMock Isolator can do the job for you with less code and ultimately more readable unit tests. I’m going to demonstrate tackling one of those limitations using MoQ as my mocking framework. Then I will tackle the same issue using TypeMock Isolator. Mocking Entity Framework with MoQ One basic need when faking Entity Framework is to fake the ObjectContext. This cannot be done by passing any connection string. You have to pass a correct Entity Framework connection string that specifies CSDL, SSDL and MSL locations along with a provider connection string. Assuming we are going to do that, we’ll explore another limitation. The limitation we are going to face now is related to not being able to fake calls to non-virtual/overridable members with MoQ. I have the following repository method that adds an EntityObject (instance of a Blog entity) to Blogs entity set in an ObjectContext. public override void Add(Blog blog) { if(BlogContext.Blogs.Any(b=>b.Name == blog.Name)) { throw new InvalidOperationException("Blog with same name already exists!"); } BlogContext.AddToBlogs(blog); } The method does a very simple check that the name of the new Blog entity instance doesn’t exist. This is done through the simple LINQ query above. If the blog doesn’t already exist it simply adds it to the current context to be saved when SaveChanges of the ObjectContext instance (e.g. BlogContext) is called. However, if a blog with the same name exits, and exception (InvalideOperationException) will be thrown. Let us now create a unit test for the Add method using MoQ. [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void Add_Should_Throw_InvalidOperationException_When_Blog_With_Same_Name_Already_Exits() { //(1) We shouldn't depend on configuration when doing unit tests! But, //its a workaround to fake the ObjectContext string connectionString = ConfigurationManager .ConnectionStrings["MyBlogConnString"] .ConnectionString; //(2) Arrange: Fake ObjectContext var fakeContext = new Mock<MyBlogContext>(connectionString); //(3) Next Line will pass, as ObjectContext now can be faked with proper connection string var repo = new BlogRepository(fakeContext.Object); //(4) Create fake ObjectQuery<Blog>. Will be used to substitute MyBlogContext.Blogs property var fakeObjectQuery = new Mock<ObjectQuery<Blog>>("[Blogs]", fakeContext.Object); //(5) Arrange: Set Expectations //Next line will throw an exception by MoQ: //System.ArgumentException: Invalid setup on a non-overridable member fakeContext.SetupGet(c=>c.Blogs).Returns(fakeObjectQuery.Object); fakeObjectQuery.Setup(q => q.Any(b => b.Name == "NewBlog")).Returns(true); //Act repo.Add(new Blog { Name = "NewBlog" }); } This test method is checking to see if the correct exception ([ExpectedException(typeof(InvalidOperationException))]) is thrown when a developer attempts to Add a blog with a name that’s already exists. On (1) a connection string is initialized from configuration file. To retrieve the full connection string. On (2) a fake ObjectContext is being created. The ObjectContext here is MyBlogContext and its being created using this var fakeContext = new Mock<MyBlogContext>(connectionString); This way a fake context is being created using MoQ. On (3) a BlogRepository instance is created. BlogRepository has dependency on generate Entity Framework ObjectContext, MyObjectContext. And so the fake context is passed to the constructor. var repo = new BlogRepository(fakeContext.Object); On (4) a fake instance of ObjectQuery<Blog> is being created to use as a substitute to MyObjectContext.Blogs property as we will see in (5). On (5) setup an expectation for calling Blogs property of MyBlogContext and substitute the return result with the fake ObjectQuery<Blog> instance created on (4). When you run this test it will fail with MoQ throwing an exception because of this line: fakeContext.SetupGet(c=>c.Blogs).Returns(fakeObjectQuery.Object); This happens because the generate property MyBlogContext.Blogs is not virtual/overridable. And assuming it is virtual or you managed to make it virtual it will fail at the following line throwing the same exception: fakeObjectQuery.Setup(q => q.Any(b => b.Name == "NewBlog")).Returns(true); This time the test will fail because the Any extension method is not virtual/overridable. You won’t be able to replace ObjectQuery<Blog> with fake in memory collection to test your LINQ to Entities queries. Now lets see how replacing MoQ with TypeMock Isolator can help. Mocking Entity Framework with TypeMock Isolator The following is the same test method we had above for MoQ but this time implemented using TypeMock Isolator: [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void Add_New_Blog_That_Already_Exists_Should_Throw_InvalidOperationException() { //(1) Create fake in memory collection of blogs var fakeInMemoryBlogs = new List<Blog> {new Blog {Name = "FakeBlog"}}; //(2) create fake context var fakeContext = Isolate.Fake.Instance<MyBlogContext>(); //(3) Setup expected call to MyBlogContext.Blogs property through the fake context Isolate.WhenCalled(() => fakeContext.Blogs) .WillReturnCollectionValuesOf(fakeInMemoryBlogs.AsQueryable()); //(4) Create new blog with a name that already exits in the fake in memory collection in (1) var blog = new Blog {Name = "FakeBlog"}; //(5) Instantiate instance of BlogRepository (Class under test) var repo = new BlogRepository(fakeContext); //(6) Acting by adding the newly created blog () repo.Add(blog); } When running the above test method it will pass as the Add method of BlogRepository is going to throw an InvalidOperationException which is the expected behaviour. Nothing prevents us from faking out the database interaction! Even faking ObjectContext  at (2) didn’t require a connection string. On (3) Isolator sets up a faking result for MyBlogContext.Blogs when its being called through the fake instance fakeContext created on (2). The faking result is just an in-memory collection declared an initialized on (1). Finally at (6) action we call the Add method of BlogRepository passing a new Blog instance that has a name that’s already exists in the fake in-memory collection which we set up at (1). As expected the test will pass because it will throw the expected exception defined on top of the test method - InvalidOperationException. TypeMock Isolator succeeded in faking Entity Framework with ease. Conclusion We explored how to write a simple unit test using TypeMock Isolator for code which is using Entity Framework. We also explored a few of the limitations of other mocking frameworks which TypeMock is successfully able to handle. There are workarounds that you can use to overcome limitations when using MoQ or Rhino Mock, however the workarounds will require you to write more code and your tests will likely be more complex. For a comparison between different mocking frameworks take a look at this document produced by TypeMock. You might also want to check out this open source project to compare mocking frameworks. I hope you enjoyed this post Muhammad Mosa http://mosesofegypt.net/ http://twitter.com/mosessaur Screencast of unit testing Entity Framework Related Links GuestPost: Introduction to Mocking GuesPost: Typemock Isolator – Much more than an Isolation framework

    Read the article

  • Ubuntu 14.04: After login, top- and sidepanel don't load and system settings don't open

    - by Löwe Simon
    I have Ubuntu 14.04 on a Medion Erazer with the Nvidia GTX570M card. At first, while I had not installed the last nvidia driver, each time I would try to suspend my pc it would freeze frame on the login. Once I managed to install the nvidia drivers, everything seemed to work up until I noticed that suddenly the system settings would not open anymore. I then rebooted my pc, but when I logged in I just end up with my cursor but no top panel or side pannel. Thankfully, I had installed the gnome desktops which works, except for the fact the system settings do not open also in the gnome desktop. I have tried following: Problems after upgrading to 14.04 (only background and pointer after login) except for reinstalling nvidia, since then I would be back at square one with suspend not working. When I try to launch system settings through the terminal, I get: simon@simon-X681X:~$ unity-control-center libGL error: No matching fbConfigs or visuals found libGL error: failed to load driver: swrast (unity-control-center:2806): Gdk-ERROR **: The program 'unity-control-center' received an X Window System error. This probably reflects a bug in the program. The error was 'BadLength (poly request too large or internal Xlib length erro'. (Details: serial 229 error_code 16 request_code 155 (GLX) minor_code 1) (Note to programmers: normally, X errors are reported asynchronously; that is, you will receive the error a while after causing it. To debug your program, run it with the GDK_SYNCHRONIZE environment variable to change this behavior. You can then get a meaningful backtrace from your debugger if you break on the gdk_x_error() function.) Trace/breakpoint trap (core dumped) I know the 2 problems seem unrelated, but since they occured together, I am wondering if that is really the case. Your help is much appreciated, Simon

    Read the article

  • Overriding component behavior

    - by deft_code
    I was thinking of how to implement overriding of behaviors in a component based entity system. A concrete example, an entity has a heath component that can be damaged, healed, killed etc. The entity also has an armor component that limits the amount of damage a character receives. Has anyone implemented behaviors like this in a component based system before? How did you do it? If no one has ever done this before why do you think that is. Is there anything particularly wrong headed about overriding component behaviors? Below is rough sketch up of how I imagine it would work. Components in an entity are ordered. Those at the front get a chance to service an interface first. I don't detail how that is done, just assume it uses evil dynamic_casts (it doesn't but the end effect is the same without the need for RTTI). class IHealth { public: float get_health( void ) const = 0; void do_damage( float amount ) = 0; }; class Health : public Component, public IHealth { public: void do_damage( float amount ) { m_damage -= amount; } private: float m_health; }; class Armor : public Component, public IHealth { public: float get_health( void ) const { return next<IHealth>().get_health(); } void do_damage( float amount ) { next<IHealth>().do_damage( amount / 2 ); } }; entity.add( new Health( 100 ) ); entity.add( new Armor() ); assert( entity.get<IHealth>().get_health() == 100 ); entity.get<IHealth>().do_damage( 10 ); assert( entity.get<IHealth>().get_health() == 95 ); Is there anything particularly naive about the way I'm proposing to do this?

    Read the article

  • IF adding new Entity gives error me : EntityCommandCompilationException was unhandled bu user code

    - by programmerist
    i have 5 tables in started projects. if i adds new table (Urun enttiy) writing below codes: project.BAL : public static List<Urun> GetUrun() { using (GenoTipSatisEntities genSatisUrunCtx = new GenoTipSatisEntities()) { ObjectQuery<Urun> urun = genSatisUrunCtx.Urun; return urun.ToList(); } } if i receive data form BAL in UI.aspx: using project.BAL; namespace GenoTip.Web.ContentPages.Satis { public partial class SatisUrun : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { FillUrun(); } } void FillUrun() { ddlUrun.DataSource = SatisServices.GetUrun(); ddlUrun.DataValueField = "ID"; ddlUrun.DataTextField = "Ad"; ddlUrun.DataBind(); } } } i added URun later. error appears ToList method: EntityCommandCompilationException was unhandled bu user code error Detail: Error 1 Error 3007: Problem in Mapping Fragments starting at lines 659, 873: Non-Primary-Key column(s) [UrunID] are being mapped in both fragments to different conceptual side properties - data inconsistency is possible because the corresponding conceptual side properties can be independently modified. C:\Users\pc\Desktop\GenoTip.Satis\GenoTip.DAL\ModelSatis.edmx 660 15 GenoTip.DAL Error 2 Error 3012: Problem in Mapping Fragments starting at lines 659, 873: Data loss is possible in FaturaDetay.UrunID. An Entity with Key (PK) will not round-trip when: (PK does NOT play Role 'FaturaDetay' in AssociationSet 'FK_FaturaDetay_Urun' AND PK is in 'FaturaDetay' EntitySet) C:\Users\pc\Desktop\GenoTip.Satis\GenoTip.DAL\ModelSatis.edmx 874 11 GenoTip.DAL Error 3 Error 3012: Problem in Mapping Fragments starting at lines 659, 873: Data loss is possible in FaturaDetay.UrunID. An Entity with Key (PK) will not round-trip when: (PK is in 'FaturaDetay' EntitySet AND PK does NOT play Role 'FaturaDetay' in AssociationSet 'FK_FaturaDetay_Urun' AND Entity.UrunID is not NULL) C:\Users\pc\Desktop\GenoTip.Satis\GenoTip.DAL\ModelSatis.edmx 660 15 GenoTip.DAL Error 4 Error 3007: Problem in Mapping Fragments starting at lines 748, 879: Non-Primary-Key column(s) [UrunID] are being mapped in both fragments to different conceptual side properties - data inconsistency is possible because the corresponding conceptual side properties can be independently modified. C:\Users\pc\Desktop\GenoTip.Satis\GenoTip.DAL\ModelSatis.edmx 749 15 GenoTip.DAL Error 5 Error 3012: Problem in Mapping Fragments starting at lines 748, 879: Data loss is possible in Satis.UrunID. An Entity with Key (PK) will not round-trip when: (PK does NOT play Role 'Satis' in AssociationSet 'FK_Satis_Urun' AND PK is in 'Satis' EntitySet) C:\Users\pc\Desktop\GenoTip.Satis\GenoTip.DAL\ModelSatis.edmx 880 11 GenoTip.DAL Error 6 Error 3012: Problem in Mapping Fragments starting at lines 748, 879: Data loss is possible in Satis.UrunID. An Entity with Key (PK) will not round-trip when: (PK is in 'Satis' EntitySet AND PK does NOT play Role 'Satis' in AssociationSet 'FK_Satis_Urun' AND Entity.UrunID is not NULL) C:\Users\pc\Desktop\GenoTip.Satis\GenoTip.DAL\ModelSatis.edmx 749 15 GenoTip.DAL

    Read the article

  • VS 2010 and Entity Framework: accessing SQL Server 2000 databases

    - by pcampbell
    Consider a Visual Studio 2010 project whose requirement is to model the data using Entity Framework. The datasource is a SQL Server 2000 database. The first step is creating a new ADO.NET Entity Data Model item. The Entity Data Model Wizard prompts for a Data Connection. When creating a new Connection, you will need to use a provider other than SqlClient. Usually it's SQLOLEDB. The list of data providers only has SqlClient or ".NET Framework Data Provider for SQL Server". Is there a work-around for Visual Studio 2010 to create or use data connections to SQL Server 2000 using the Entity Framework?

    Read the article

  • A list of Entity Framework providers for various databases

    - by Robert Koritnik
    Which providers are there and your experience using them I would like to know about all possible native .net Framework Entity Framework providers that are out there as well as their limitations compared to the default Linq2Entities (from MS for MS SQL). If there are more for the same database even better. Tell me and I'll be updating this post with this list. Feel free to add additional providers directly into this post or provide an answer and others (including me) will add it to the list. Entity Framework 1 Microsoft SQL Server Standard/Enterprise/Express Linq 2 Entities - Microsoft SQL Server connector DataDirect ADO.NET Data Providers Microsoft SQL Server CE (Compact Edition) Any provider? MySQL MySQL Connector (since version 6.0) - I've read about issues when using Skip(), Take() and Sort() in the same expression tree - everyone welcome to input their experience/knowledge regarding this. (NOTE: MySQL Connector/NET Visual Studio Integration is not supported in the Express Editions of Visual Studio, meaning you won't be able to view MySQL databases in the Database explorer window or add a MySQL data source via Visual Studio wizard dialog boxes. Some users may find that this limits their ability to use Entity Framework and MySQL within Visual Studio Express). Devart dotConnect for MySQL - similar issues to MySql's connector as I've read and both try to blame MS for it [these issues are supposed to be solved] SQLite Devart dotConnect for SQLite System.Data.SQLite PostgreSQL Devart dotConnect for PostgreSQL Npgsql Oracle Devart dotConnect for Oracle Sample Entity Framework Provider for Oracle - community effort project DataDirect ADO.NET Data Providers DB2 IBM Data Server Provider has EF support. Here are some limitations. DataDirect ADO.NET Data Providers Sybase Sybase iAnywhere DataDirect ADO.NET Data Providers Informix IBM Data Server Provider supports Informix Firebird ADO.NET Data Provider with EF support Provider Wrappers Tracing and Caching Providers for EF Entity Framework 4 (beta) Microsoft SQL Server Microsoft's Linq to Entities 4 - shipped with .net 4.0 and Visual Studio 2010; so far the only provider for EF4 MySQL Devart dotConnect for MySQL SQLite Devart dotConnect for SQLite PostgreSQL Devart dotConnect for PostgreSQL Oracle Devart dotConnect for Oracle

    Read the article

  • Entity Framework - SaveChanges with GUID as EntityKey

    - by MissingLinq
    I have a SQL Server 2008 database table that uses uniqueidentifier as a primary key. On inserts, the key is generated on the database side using the newid() function. This works fine with ADO.NET. But when I set up this table as an entity in an Entity Framework 4 model, there's a problem. I am able to query the entity just fine, but when creating a new entity and invoking SaveChanges() on the context, the generated uniqueidentifier on the database is all zeros. I understand there was an issue with EF v1 where this scenario did not work, requiring creating the GUID on the client prior to calling SaveChanges. However, I had read in many places that they were planning to fix this in EF 4. My question -- is this scenario (DB-side generation of uniqueidentifier) still not supported in EF4? Are we still stuck with generating the GUID on the client?

    Read the article

  • Partial mapping in Entity Framework 4

    - by Dimi Toulakis
    Hi guys, I want to be able to do the following: I have a model and inside there I do have an entity. This entity has the following structure: public class Client { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } } What I want now, is to just get the client name based on the id. Therefore I wrote a stored procedure which is doing this. CREATE PROCEDURE [Client].[GetBasics] @Id INT AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; SELECT Name FROM Client.Client INNER JOIN Client.Validity ON ClientId = Client.Id WHERE Client.Id = @Id; END Now, going back to VS, I do update the model from the database with the stored procedure included. Next step is to map this stored procedure to the client entity as a function import. This also works fine. Trying now to load one client's name results into an error during runtime... "The data reader is incompatible with the specified 'CSTestModel.Client'. A member of the type, 'Id', does not have a corresponding column in the data reader with the same name." I am OK with the message. I know how to fix this (returning as resultset Id, Name, Description). My idea behind this question is the following: I just want to load parts of the entity, not the complete entity itself. Is there a solution to my problem (except creating complex types)? And if yes, can someone point me to the right direction? Many thanks, Dimi

    Read the article

  • Help with editing data in entity framework.

    - by Levelbit
    Title of this question is simple because there is no an easy explanation for what I'm trying to ask you. I hope you'll understand in the end :). I have to tables in my database: Company and Location (relationship:one to many) and corresponding entity sets. In my wpf application I have some datagrid which I want to fill with locations and to be able to edit every row in separate window as some form of details view (so I don't want to edit my data in datagrid). I did this by accessing Location entity from selected row and creating a new Location entity and then I copy properties from original entity to newly created. Something like cloning the object. After editing if I press OK changed data is copied to original object back, and if I press Cancel nothing happens. Of course, you probably thinking I could use NoTracking option and AttachAsModified method as was mentioned as solution in some earlier questions(see:http://stackoverflow.com/questions/803022/changing-entities-in-the-entityframework) by Alex James, but lets say I had some problems about that and I have my own reasons for doing this. Finally, because navigation property(Company) of my location entity is assigned to newly created location object(during cloning) from some reason in object context additional object as copy of object I want to edit from datagrid is created without my will(similar problem :http://blogs.msdn.com/alexj/archive/2009/12/02/tip-47-how-fix-up-can-make-it-hard-to-change-relationships.aspx). So, when I do ObjectContext.SaveChanges it inserts additional row of data into my database table Location, the same as the one i wanted to edit. I read about sth like this, but I don't quite understand why is that and how to block or override this. I hope I was clear as I could. Please, solutions or some other ideas.

    Read the article

  • Entity Framework and Sql Server view question

    - by Sergio Romero
    Hi to all, For several reasons that I don't have the liberty to talk about, we are defining a view on our Sql Server 2005 database like so: CREATE VIEW [dbo].[MeterProvingStatisticsPoint] AS SELECT CAST(0 AS BIGINT) AS 'RowNumber', CAST(0 AS BIGINT) AS 'ProverTicketId', CAST(0 AS INT) AS 'ReportNumber', GETDATE() AS 'CompletedDateTime', CAST(1.1 AS float) AS 'MeterFactor', CAST(1.1 AS float) AS 'Density', CAST(1.1 AS float) AS 'FlowRate', CAST(1.1 AS float) AS 'Average', CAST(1.1 AS float) AS 'StandardDeviation', CAST(1.1 AS float) AS 'MeanPlus2XStandardDeviation', CAST(1.1 AS float) AS 'MeanMinus2XStandardDeviation' WHERE 0 = 1 The idea is that the Entity Framework will create an entity based on this query, which it does, but it generates it with an error that states the following: "warning 6002: The table/view 'Keystone_Local.dbo.MeterProvingStatisticsPoint' does not have a primary key defined. The key has been inferred and the definition was created as a read-only table/view." And it decides that the CompletedDateTime field will be this entity primary key. We are using EdmGen to generate the model. Is there a way not to have the entity framework include any field of this view as a primary key? Thanks for help.

    Read the article

  • Should the entity framework + self tracking entities be saving me time

    - by sipwiz
    I've been using the entity framework in combination with the self tracking entity code generation templates for my latest silverlight to WCF application. It's the first time I've used the entity framework in a real project and my hope was that I would save myself a lot of time and effort by being able to automatically update the whole data access layer of my project when my database schema changed. Happily I've found that to be the case, updating my database schema by adding a new table, changing column names, adding new columns etc. etc. can be propagated to my business object classes by using the update from database option on the entity framework model. Where I'm hurting is the CRUD operations within my WCF service in response to actions on my Silverlight client. I use the same self tracking entity framework business objects in my Silverlight app but I find I'm continually having to fight against problems such as foreign key associations not being handled correctly when updating an object or the change tracker getting confused about the state of an object at the Silverlight end and the data access operation within the WCF layer throwing a wobbly. It's got to a point where I have now spent more time dealing with this quirks than I have on my previous project where I used Linq-to-SQL as the starting point for rolling my own business objects. Is it just me being hopeless or is the self tracking entities approach something that should be avoided until it's more mature?

    Read the article

  • How do I get entity for primary key using EntityDataSource in ASP.NET

    - by drasto
    I have a GridView in my ASP.NET application that takes data to be rendered from EntityDataSource. GridView allows user to select rows. I want to get the entity that corresponds to the row user selected. I can get from GridView the ID(primary key) of the entity that corresponds to the row selected. How can I get the Entity that has that ID(primary key) ?

    Read the article

  • How to map EnumSet (or List of Enums) in an entity using JPA2

    - by arteq007
    I have entity Person: @Entity @Table(schema="", name="PERSON") public class Person { List<PaymentType> paymentTypesList; //some other fields //getters and setters and other logic } and I have enum PaymentType: public enum PaymentType { FIXED, CO_FINANCED, DETERMINED; } how to persist Person and its list of enums (in this list i have to place variable amount of enums, there may be one of them, or two or all of them) I'm using Spring with Postgres, Entity are created using JPA annotation, and managed using Hibernate

    Read the article

  • Entity Framework - avoiding another query

    - by adamjellyit
    I have a requirement to only save data to a table in a database (I don't need to read it) If the record already exists I want to update it otherwise I will add it. It usually exists. My entity context might already hold the object .. if it does I want to find it and use it again without causing it to refresh from the database when I 'find' it i.e. The context holds a collection of entities (rows of a database) I want to find an entity in the collection and only want the context to go to the database if entity is not in the collection. I don't care about the current values of the entity .. I just want to update them. Hope this is clear ..... thanks

    Read the article

  • Using Entity Framework as Data Access Layer

    - by AJM
    In my ASP.NET application I want to implement by data acess layer using the Entity framweok so I can use it as an ORM tool. But I dont want the rest of the application to care that I'm using this or be polluted by anything entity frameowrk specific. I cant seem to find anyone who is using the entity framework exclusively in their Data access layer so I'm keen to see any online examples of this/ experience people have.

    Read the article

  • Entity framework unit testing with sqlite

    - by Marcus Malmgren
    Is it possible to unit test Entity Framework v2 repositories with SqLite? Is this only possible if my entities are plain Poco and not automatically generated by Entity Framework? I've generated a entity model from SqlServer and in the generated .edmx file i found this in section SSDL content: Provider="System.Data.SqlClient". Correct me if I am wrong, but shouldnt that be System.Data.SQLite in order to work with sqlite?

    Read the article

  • Adding an ADO.NET Entity Data Model throws build errors

    - by user3726262
    I am using Visual Studio 2013 express. I create a new project and then I add a database to that project. But, when I add an ADO.NET Entity Framework model to that project and then run the program, I get the following four build errors listed below. To try to remedy this myself, I added the namespaces 'System.Data.Entity' and 'System.Data.Entity.Design', but that didn't help. Also, I uninstalled and re-installed the Nuget package. I also uninstalled and re-installed Visual Studio 2013 Express for Windows Desktop. But these measures didn't help the situation either. Please note that I used to use the Entity Data model just fine. But it was around the time that I did a system restore on my computer, and when I updated VS 2013 with an update offered on the start page, and finally, when I signed up for MS Azure, that I started running into the problem described above. Now I would think that uninstalling and reinstalling Visual Studio 2013, and then installing the 'Nuget' Package would solve all problems. What am I missing here? The errors mentioned above are: Error 1 The type or namespace name 'Infrastructure' does not exist in the namespace 'System.Data.Entity' (are you missing an assembly reference?) C:\Users\John\documents\visual studio 2013\Projects\Riches\Riches\RichesModel.Context.cs 14 30 DataLayer Error 2 The type or namespace name 'DbContext' could not be found (are you missing a using directive or an assembly reference?) C:\Users\John\documents\visual studio 2013\Projects\Riches\Riches\RichesModel.Context.cs 16 52 DataLayer Error 3 The type or namespace name 'DbModelBuilder' could not be found (are you missing a using directive or an assembly reference?) C:\Users\John\documents\visual studio 2013\Projects\Riches\Riches\RichesModel.Context.cs 23 49 DataLayer Error 4 The type or namespace name 'DbSet' could not be found (are you missing a using directive or an assembly reference?) C:\Users\John\documents\visual studio 2013\Projects\Riches\Riches\RichesModel.Context.cs 28 16 DataLayer Thank you and I realize that my last attempt at this question was rather rough-draftish, John

    Read the article

  • Entity Framework + stored procedure with paging

    - by Eatdoku
    I am using Entity Framework now and using a stored procedure to populate my entity. Where there is no problem with populating my entity, but when i trying to bind the result to a gridview control with "Enable Paging" set to true, it gives an error saying "The data source does not support server-side data paging." I am using stored procedure because one of the table column is FullTextIndexed, and there is a requirement to be able to search on that field. Can anyone tell me how the paging would work in this situation?

    Read the article

  • Symfony2 Entity to array

    - by Adriano Pedro
    I'm trying to migrate my flat php project to Symfony2, but its coming to be very hard. For instance, I have a table of Products specification that have several specifications and are distinguishables by its "cat" attribute in that Extraspecs DB table. Therefore I've created a Entity for that table and want to make an array of just the specifications with "cat" = 0... I supose the code is this one.. right? $typeavailable = $this->getDoctrine() ->getRepository('LabsCatalogBundle:ProductExtraspecsSpecs') ->findBy(array('cat' => '0')); Now how can i put this in an array to work with a form like this?: form = $this ->createFormBuilder($product) ->add('specs', 'choice', array('choices' => $typeavailableArray), 'multiple' => true) Thank you in advance :) # Thank you all.. But now I've came across with another problem.. In fact i'm building a form from an existing object: $form = $this ->createFormBuilder($product) ->add('name', 'text') ->add('genspec', 'choice', array('choices' => array('0' => 'None', '1' => 'General', '2' => 'Specific'))) ->add('isReg', 'choice', array('choices' => array('0' => 'Material', '1' => 'Reagent', '2' => 'Antibody', '3' => 'Growth Factors', '4' => 'Rodents', '5' => 'Lagomorphs'))) So.. in that case my current value is named "extraspecs", so i've added this like: ->add('extraspecs', 'entity', array( 'label' => 'desc', 'empty_value' => ' --- ', 'class' => 'LabsCatalogBundle:ProductExtraspecsSpecs', 'property' => 'specsid', 'query_builder' => function(EntityRepository $er) { return $er ->createQueryBuilder('e'); But "extraspecs" come from a relationship of oneToMany where every product has several extraspecs... Here is the ORM: Labs\CatalogBundle\Entity\Product: type: entity table: orders__regmat id: id: type: integer generator: { strategy: AUTO } fields: name: type: string length: 100 catnumber: type: string scale: 100 brand: type: integer scale: 10 company: type: integer scale: 10 size: type: decimal scale: 10 units: type: integer scale: 10 price: type: decimal scale: 10 reqcert: type: integer scale: 1 isReg: type: integer scale: 1 genspec: type: integer scale: 1 oneToMany: extraspecs: targetEntity: ProductExtraspecs mappedBy: product Labs\CatalogBundle\Entity\ProductExtraspecs: type: entity table: orders__regmat__extraspecs fields: extraspecid: id: true type: integer unsigned: false nullable: false generator: strategy: IDENTITY regmatid: type: integer scale: 11 spec: type: integer scale: 11 attrib: type: string length: 20 value: type: string length: 200 lifecycleCallbacks: { } manyToOne: product: targetEntity: Product inversedBy: extraspecs joinColumn: name: regmatid referencedColumnName: id HOw should I do this? Thank you!!!

    Read the article

  • How to make Entity Key Mapping in Entity Framework like sql's foreign key?

    - by programmerist
    I try to give entity map on my entity app. But how can I do it? I try to make it like below: var test = ( from k in Kartlar where k.Rehber..... above codes k.(can not see Rehber or not working ) if you are correct , i can write k.Rehber.ID and others. i can not write: from k in Kartlar where k.Rehber.ID = 123 //assuming that navigation property name is Rehbar and its primary key of Rehbar table is ID && k.Kampanya.ID = 345 //assuming that navigation property name is Kampanya and its primary //key of Kampanya table is ID && k.Birim.ID = 567 //assuming that navigation property name is Birim and its primary key of Birim table is ID select k images you can see: also: You should look : http://i42.tinypic.com/2nqyyc6.png I have a table it includes 3 foreign key field like that: My Table: Kartlar ID (Pkey) RehberID (Fkey) KampanyaID (Fkey) BrimID (Fkey) Name Detail How can i write entity query with LINQ ? select * from Kartlar where RehberID=123 and KampanyaID=345 and BrimID=567 BUT please be careful I can not see RehberID, KampanyaID, BrimID in entity they are foreign key. I should use entity key but how?

    Read the article

  • Storing a jpa entity where only the timestamp changes results in updates rather than inserts (desire

    - by David Schlenk
    I have a JPA entity that stores a fk id, a boolean and a timestamp: @Entity public class ChannelInUse implements Serializable { @Id @GeneratedValue private Long id; @ManyToOne @JoinColumn(nullable = false) private Channel channel; private boolean inUse = false; @Temporal(TemporalType.TIMESTAMP) private Date inUseAt = new Date(); ... } I want every new instance of this entity to result in a new row in the table. For whatever reason no matter what I do it always results in the row getting updated with a new timestamp value rather than creating a new row. Even tried to just use a native query to run an insert but channel's ID wasn't populated yet so I gave up on that. I've tried using an embedded id class consisting of channel.getId and inUseAt. My equals and hashcode for are: public boolean equals(Object obj){ if(this == obj) return true; if(!(obj instanceof ChannelInUse)) return false; ChannelInUse ciu = (ChannelInUse) obj; return ( (this.inUseAt == null ? ciu.inUseAt == null : this.inUseAt.equals(ciu.inUseAt)) && (this.inUse == ciu.inUse) && (this.channel == null ? ciu.channel == null : this.channel.equals(ciu.channel)) ); } /** * hashcode generated from at, channel and inUse properties. */ public int hashCode(){ int hash = 1; hash = hash * 31 + (this.inUseAt == null ? 0 : this.inUseAt.hashCode()); hash = hash * 31 + (this.channel == null ? 0 : this.channel.hashCode()); if(inUse) hash = hash * 31 + 1; else hash = hash * 31 + 0; return hash; } } I've tried using hibernate's Entity annotation with mutable=false. I'm probably just not understanding what makes an entity unique or something. Hit the google pretty hard but can't figure this one out.

    Read the article

  • Entity Framework with 'Get' Stored Procedure that returns Entities

    - by Nick Reeve
    Hello, I am attempting to execute a stored procedure that returns data with exactly the same columns as that of a table Entity I have in my project. I set the 'Returns a Collection Of' property in the 'Add Function Import' dialog to my entity type. I get a NullReferenceException error when executing the stored procedure and on further digging it seems that it is because the 'EntityKey' property is missing. Is there anything I can do to tell it to ignore those special properties of the Entity? I already have a partial class for that entity with '[ScaffoldColumn(false)]' but that doesn't seem to matter. Cheers, Nick

    Read the article

  • Entity Framework projections

    - by David McClelland
    We are investigating the Entity Framework to see if it will meet our particular needs. Here is the scenario I am interested in: I have a large table (let's call it VeryWideRecord) which has many columns, and it has a corresponding business object (it's also called VeryWideRecord). I would like to be able to query my database for a VeryWideRecord business object, but only have values for certain columns returned by the underlying SQL. Can I do this with the Entity Framework? I am uncertain as to whether this could be done with the Entity Framework's table splitting feature, because the application needs to be able (at runtime) to change the columns that are requested. The reason for this is that we are trying to minimize the amount of information that is going across the wire. I see how this could be done using NHibernate (example), but how can I do this with the Entity Framework?

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >