w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Entity Framework Code First Table-Per-Type Inheritance include base type
The answer was to remove the abstract keyword from the Base class (Person): FROM: public abstract class Person { public string FirstName { get; set; } public string LastName { get; set; } public Training Training { get; set; } } TO: public class Person { public string FirstName { get; set; } public string LastName { get; set; } public Training Training { get; set; } }

Categories : C#

Entity Framework Code First: Computed property of type Type causes ArgumentNullException on Update-Database
Use NotMappedAttribute: Denotes that a property or class should be excluded from database mapping.

Categories : C#

Store data both in base and derived tables in Table-per-type inheritance in Entity Framework
In your DbContext's OnModelCreating override, use the following: protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Base>().Map(m => { m.ToTable("Base"); }); modelBuilder.Entity<Derived>().Map(m => { m.MapInheritedProperties(); m.ToTable("Derived"); }); }

Categories : Entity Framework

How should custom code be run during an Entity Framework database migration?
A migration represents a change in the schema, therefor you can't use AddOrUpdate() stuff inside a migration. But you can, and this is what I would suggest you, run plain SQL code using the Sql() method.

Categories : C#

How to factor type parameters out of my code that uses DynamicMethod and Entity Framework?
If you want to do true dynamic calls, where the calling site is also dealing with runtime fields then There are 2 basic approaches to Dynamic Expressions and Queries in LINQ. a) String Dynamic Lambda System.Linq.Dynamic can be found at following links http://msdn.microsoft.com/en-US/vstudio/bb894665.aspx http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx http://www.scottgu.com/blogposts/dynquery/dynamiclinqcsharp.zip b) Build Expression trees More powerful but harder to master... Build expressions trees with code found here: http://msdn.microsoft.com/en-us/library/system.linq.expressions.aspx However if you only need the Resposityory pattern generic and the calling site will know can supply the predicates then something

Categories : C#

Entity Framework 5 table-per-type update, change sub type but keep same base type
I don't have a good answer, but I can think of four "solutions" that are really workarounds: Don't use DBMS-computed values for your primary keys (if you already use natural keys, it's fine). Use DBMS-computed surrogate keys. Follow something like the state pattern. Do some evil voodoo with the object state manager. Update: There seems to be a popular consensus that trying isn't even worth it; most people thus simply use stored procedures instead to work around the problem. Changing Inherited Types in Entity Framework Entity Framework: Inheritance, change object type Changing the type of an (Entity Framework) entity that is part of an inheritance hierarchy Changing the type of an entity that is part of an inheritance hierarchy Using natural keys First, remember that the objects tr

Categories : Entity Framework

What is a possible interface to return for Entity framework entity classes?
What about a generic repository Pattern? public interface IRepository<T> { List<string> GetColumnNames(); IQueryable<T> GetAll(); } public class CatalogItemRepository : IRepository<CatalogItem> { private string repositoryName="CatalogItem"; public List<string> GetColumnNames() { //implementation } public IQueryable<CatalogItem> GetAll() { //implementation } }

Categories : C#

Entity Framework 6 RC 1 issue - Could not load type 'System.Data.Entity.Config.SingletonDependencyResolver`1'
I also get an error after updating to RC1 when trying to add mapping classes to the model builder using: modelBuilder.Configurations.AddFromAssembly(Assembly.GetExecutingAssembly()); Error: {"Method not found: 'System.Data.Entity.ModelConfiguration.Configuration.PrimitivePropertyConfiguration1<System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration> System.Data.Entity.ModelConfiguration.Configuration.StructuralTypeConfiguration1.Property(System.Linq.Expressions.Expression1<System.Func2>)'."} Rolling back to beta 1 also fixes my issue. Seems like some types have been moved into different namespaces.

Categories : C#

Self referencing entity & insert order - using Entity Framework Code First
I have had the same error with foreign keys using EF. It may not be related however the answer that was provided helped me understand why I was getting the error. Issue with EF and Foreign keys In summary of Slauma's answer I was clearing the vertical navigation values before my EF insert. This caused an issue, all-though it is a different issue it may help. Potential Solution If you where to all your AssetSession object to your Asset object and then do one root add that should allow EF to insert both correctly. Note: To do this you may need to generate your GUID in advance of inserting your objects.

Categories : C#

c# entity framework 5 code first map three part table name to entity
This feature does not exist in Entity Framework. There is a change request that currently has status "Under Review" (which can mean anything, but at least it's not rejected - yet). The closest you can get is using synonyms as described here. But synonyms are easily broken!

Categories : C#

Using .net functions to filter Entity Framework information
This will be very slow, as it has to retrieve the entire table from the database and then it will filter, but this is what you want: var res=Items.ToList().Where(i=>IntegralUtils.RegionalArea(i.X,i.Y)); If you prefer the query syntax, I believe this will work as well: var res=from item in Items.ToList() where IntegralUtils.RegionalArea(item.X, item.Y) select item;

Categories : Dotnet

Do Entity Framework Provide Utility that convert DB Type To C# Type?
I dont know such a public method (I think there is none... it that may be accepted as answer) However, try to uncompile sqlmetal.exe, you can have a good idea of how default associations are implemented internally: In class LinqToSqlShared.Utility.DbTypeSystem (internal class) you can find the method: internal static Type GetClosestRuntimeType(SqlDbType sqlDbType) { switch (sqlDbType) { case SqlDbType.BigInt: return typeof(long); case SqlDbType.Binary: case SqlDbType.Image: case SqlDbType.Timestamp: case SqlDbType.VarBinary: return typeof(Binary); case SqlDbType.Bit: return typeof(bool); case SqlDbType.Char: case SqlDbType.NChar: case SqlDbType.NText: case SqlDbType.NVarChar: case SqlDbType.Text: case SqlDbType.

Categories : C#

How to store variable 2D array via Entity Framework?
To me a 2D array sounds like (x,y) = somevalue. So I'm thinking of something simple, something like this (assuming somevalue is an int): public interface IArrayValueEntity { int ArrayIndexX { get; set; } int ArrayIndexY { get; set; } int Value { get; set; } } The entity type implements it like this (or you can have just the implementation if you prefer): public class ArrayValue : IArrayValueEntity { public int ArrayIndexX { get; set; } public int ArrayIndexY { get; set; } public int Value { get; set; } } Then you can make ArrayIndexX and ArrayIndexY be entity's primary key (and have EF enforce uniqueness of combinations of these two values) in overriding the OnModelCreating method of your DbContext if you're going code-first. public class MyDbContext : Db

Categories : C#

How to store childrens of the same model with entity framework?
The way I went about it requires a few additional properties in your model (I'm using the virtual` keyword for my navigation properties because I required lazy loading): public class Page { public int Id { get; set; } public string Name { get; set; } public int? ParentID { get; set; } // Nullable int because your Parent is optional. // Navigation properties public virtual Page Parent { get; set; } // Optional Parent public virtual List<Page> Children { get; set; } } Then, using a foreign key association, you can configure the relationship like so (this is my Page mapping): // You may be configuring elsewhere, so might want to use `modelBuilder.Entity<Page>()` instead of `this` this.HasMany(t => t.Children) .WithOptional(t => t.Parent)

Categories : Entity Framework

Possible SQL-Injection with user defined functions and entity framework?
From http://msdn.microsoft.com/en-us/library/ms189760.aspx CONTAINSTABLE is used in the FROM clause of a Transact-SQL SELECT statement and is referenced as if it were a regular table name. .It performs a SQL Server full-text search on full-text indexed columns containing character-based data types. If you read Quassnoi's answer with regard to searching the full-text index for double quotes: Punctuation is ignored. Therefore, CONTAINS(testing, "computer failure") matches a row with the value, "Where is my computer? Failure to find it would be expensive." Documentation can be found here. See his answer for an alternative using the LIKE operator. To answer your questions: My question is if my app is vulnerable to SQL injections and how I should protect against them. You a

Categories : C#

Entity Framework generated code raises warnings in Code Analysis
You could try using the DbContext templates instead of ObjectContext. More info: DbContext was introduced in EF 4.1 as part of Code First and since EF5 has also become the default generated context for Db/Model-first approaches. It uses POCO entities and simplifies a lot of common tasks, which I find makes my model easier to maintain. It also wraps ObjectContext, so you can still call into that if you need to. Since it generates different code, you'd be avoiding the FxCop warnings you are currently seeing, but of course switching to DbContext would require changes to your application code.

Categories : C#

Entity framework - WCF - return JSON how to do this?
You can define XXXDto classes which are having a clean format for your client needs. And then map the domain/endity classes to Dto objects and serialize them using WCF. Or you can create WCF OData services to expose the service as OData source.

Categories : Json

Entity Framework 5 - RETURN(X) from a Stored Procedure
Your stored procedure should have an output declared. Assuming it is @result, you will need to set it and return it. CREATE PROCEDURE MySP /* Input parameters here */ @result INT OUTPUT AS BEGIN SET @result = 22 return @result END The return value of your call should be in result. var result = new ObjectParameter("result", typeof(double)); context.MySP(code, Id, result); int success = result.Value;

Categories : Entity Framework

Entity Framework Type Error
just by looking at your quety it obvious that what you are returning is a collection of .dc_tp_personnel object return (from x in db.dc_tp_personnel.Include("dc_toutside_test") where x.PersonId == 1 select x).ToList(); but in your return type you defined List<bc_limsEntities> which is the context btw, so therefore the exception you are getting is because you are retutning dc_tp_personnel but the return type is bc_limsEntities if you make return type dc_tp_personnel you should not get that exception

Categories : Asp Net Mvc

Entity Framework method to return entities as a property
You need a class that having all logics of an entity... This link will help you - Implementing Repository Pattern With Entity Framework

Categories : C#

Calling a stored procedure with nothing to return using Entity Framework
You want context.Database.ExecuteSqlCommand instead of SqlQuery context.Database.ExecuteSqlCommand( "mySpName @param1, @param2, @param3", new SqlParameter("param1", param1), new SqlParameter("param2", param2), new SqlParameter("param3", param3) );

Categories : Entity Framework

entity framework use linq to return join tables
Join tables and use anonymous type to return required fields: from t1 in table1 join t2 in table2 on t1.fk_tb2 equals t2.id2 join t3 in table3 on t2.fk_tb3 equals t3.id3 select new { t1.id1, t2.id2, t3.name3 }

Categories : C#

Entity Framework isn't getting the columns for Complex Type
@chiefGui I did not understand your question perfectly well, but seems when you click in "Get Column Information" button, you get no columns. If it's that the problem you can fix it by adding a command in you procedure. Put a command like this. ALTER PROC ProcName /* ([,parameters] ) */ AS BEGIN /* this command you make the difference */ SET FMTONLY OFF /* other code here */ END Put this in first line of inside of your procedure. Remove the procedure from EDMX, add again and try again the import. And you'll get all columns returned by your procedure. So de step by step will working well. If this is not the answer you want please add comment so I can help you. EDITED This happens because the EF try to getting columns headers without getting a result data. If your proce

Categories : C#

Entity FrameWork in Wpf Code First
Here is a simple example from MSDN. It comes with video as well as text explanation. A good point to start: http://msdn.microsoft.com/en-us/data/jj193542.aspx

Categories : Wpf

Entity Framework: One to zero/one with C# Code First
Seems to me that you need to have a UserID FK relationship between Reviewer and User. In such a design, not all users would have to be reviewers, but all reviewers would have to be a user. I also am starting to think that maybe you are over-complicating things by no utilizing a concept of roles within your system. Generally, a user vs reviewer would be specified depending upon the roles that a user has. In this manner, all users would be the same and hold the same data in the tables, the only difference would be that the users have different roles. Authorization and authentication also become simplified when using Roles vs doing complicated table joining or nullable FK relationships.

Categories : C#

Getting an type conversion error while using linq in entity framework
try using Dim standard = (From s In db.Standards Where s.StandardId = CInt(ComboSelectStandardToEdit.SelectedValue) Select s) .FirstOrDefault txtStandardName.Text = standard.StandardName your Linq query currently is returing a projection which could contain multiple entries. By explicitly requesting the first object of the projection, you won't need to cast your standard before accessing it's value.

Categories : Sql Server

what is the type of TrackableCollectionOfMyObjectNamexSjLehPL coming from EF4(entity framework)- Mvvm-WPf
1 - Delete all your current Service References. 2 - Add a reference to your Model assembly (project) from your ViewModels: --MySolution |-- MyProject.Model | |-- (Model Classes) | |-- MyProject.ViewModels | |--References | | |--MyProject.Model.dll <-- You need this | | | |--(ViewModel Classes) | |----(etcetera) This allows you to "Reuse existing Types" when creating the service reference: That will prevent that horrible TrackableCollectionOfCityxSjLehPL from ever showing up. 3 - Re-add the Service References and make sure you select the option shown above. 4 - You will probably NOT want to handle CollectionChanged in the TrackableCollection. Keep the ViewModel separate from the Model, otherwise you will run into huge maintainability / scalability iss

Categories : C#

Manipulating the returned type of Entity Framework Model First
ObjectResult is just a collection of results. You can use First(), Single(), or anything you normally would on a collection to get the result you desire. It becomes a collection because Entity Framework can never guarantee that your store procedure will always return one result.

Categories : C#

How to check if a property of an Entity Framework type is Nullable
If your properties are decorated with attributes like [Required] or [StringLength] with a property MinimumLength set to a value greater then 0, you could use that property's GetType() method. This method will return an object of type Type and it has a number of other methods like GetCustomAttributes. This method will return all the custom attributes applied to your property. As I said earlier, if you know which attributes were applied, like the ones mentioned, then using YourObject.YourProperty.GetType().GetCustomAttributes(true) will do the trick. You will need to go through the array and cast the result to the proper attribute.

Categories : C#

XML Fields with Entity Framework Code First
I think that you would have to add another property and write some code to do the serialization. This should do it: [Table("Polygons")] public class Polygon { public int PolygonId { get; set; } public String Texture { get; set; } [NotMapped] public virtual ICollection<Point> Points { get; set; } [Column("Points")] [EditorBrowsable(EditorBrowsableState.Never)] [DebuggerBrowsable(DebuggerBrowsableState.Never)] public string PointsXml { get { var serializer = new XmlSerializer(typeof (List<Point>)); using (var stringWriter = new StringWriter()) { serializer.Serialize(stringWriter, Points.ToList()); stringWriter.Flush(); return stringWriter.ToS

Categories : C#

Entity Framework Code First DB error
you need to enable EF migrations. Using Nuget Package Manager Console run, Enable-Migrations. The full tutorial is Building an Initial Model & Database The commands from the Nuget console will look similar to Enable-Migrations -ContextTypeName Table.Models.Data.DatabaseContext -EnableAutomaticMigrations -Force) and update the database afterwards (Update-Database)

Categories : C#

Entity Framework 5.0 Code First Many to Many Update
You must load Apple.Oranges first, before adding items to it. If the collection is loaded, EF's change tracker will know which associations are new and which already exist and only the new associations will be saved. You can load the collection by db.Entry(Apple).Collection(a => a.Oranges).Load() and you can remove the code if (Apple.Oranges == null) Apple.Oranges = new List<Orange>();

Categories : Entity Framework

Entity Framework Code-First One-To-One Relationship
If you are going for code first and want to have both Customer And CustomerSettings classes, but only a single table for both, as your post suggests , I would use complex types. see a good example here: http://weblogs.asp.net/manavi/archive/2010/12/11/entity-association-mapping-with-code-first-part-1-one-to-one-associations.aspx So , your object model should look like this (I've not tested it): public class Customer { public Customer() { CustomerSetting= new CustomerSetting(); } public int CustomerId { get; set; } public int Name { get; set; } public CustomerSetting CustomerSetting { get; set; } } [ComplexType] public class CustomerSetting { public int CustomerId { get; set; } public int Setting1 { get; set; } public int Setting2 { get; se

Categories : Entity Framework

Entity Framework Code First foreign key
I would suggest making the Class1, Class2, Class3, and corresponding identifiers nullable. You would have to enforce constraints at the code level though, instead of relying on the database for those constraints.

Categories : C#

Get foreign key value using Entity Framework code first
When you decorate associations with virtual you are inferring them to be lazy loaded. This means that the primary collection (in this case DeviceTypes) is loaded but, until you try to access it, Issues won't be populated with any information. There are multiple ways to get around this, but simplest (and most efficient) is load the associations when you need them using the Include method. e.g. var devices = context.DeviceTypes.Include(x => x.Issues); This will load the original collection (DeviceTypes) as well as populate the Issues for each type. This is usually the best way as you're only grabbing information you need to get your unit of work completed when it's needed. If you find this to be common, however, you can always adjust lazy loading in your DbContext constructor: publi

Categories : C#

Entity framework 6 code first - one way many to many via annotations
I think you wanna learn how to separate relations from EF code first entities. I have started a topic in here about this question. I wanna separate the relation objects from entity, and I used partial classes. In my question I wanna learn how to separate partial classes by class bilrary. But couldn't. While I was using NHibernate I was using XML mapping and creating relations here, In java platform is same thing. But I think Entity Framework is not ready yet.

Categories : C#

how to use entity framework code first the mapping about one to one
First of all you must to declare TbA MyTbA as virtual, public virtual TbA MyTbA{get;set;} (*)public int TbAid{get;set;} Then you can configure your relations on the typeConfiguration. But you need a foreignKeytoA in the B class.(*) HasRequired(x=>x.MyTbA).WithOptional().HasForeignKey(x=>x.ForeignKeytoA); if you put .withOptional(empty). thas tell to entity that class A has not foreign key to B.

Categories : C#

Can I use a datetime as a key using code-first entity framework with mvc 4?
You should be able to add the [Key] attribute to the DayOfWork property to do this. namespace TimeKeeper.Models { public class WorkDay { [Key] public DateTime DayOfWork { get; set; } public Boolean holiday { get; set; } } } See Here on stack overflow for whether this is a good idea or not.

Categories : Dotnet

Entity Framework Code First - Interfaces
Not sure it can be done, but if it can, do not use an interface but a class, please try public class Item { public int Id { get; set; } public string Name { get; set; } } public class Ingredient : Item { public double Price { get; set; } } public class Recipe : Item { public List<RecipeItem> RecipeItems { get; set; } } public class RecipeItem { public int Id { get; set; } public Item Item { get; set; } public double Quantity { get; set; } } Then you may want to read about EF and TPH

Categories : C#

Entity Framework 1 to 1 relationship using code first. how?
This occurs in CodeFirst because of the virtual keyword. In effect, you are creating a relationship where creating one item requires the creation of the other. however, the virtual keyword allows lazy instantiation, which means that creating an object of one type doesn't automatically create the other type, allowing the Id on the foreign item to be null. This implies a 0..1 relationship, but since each side is virtual, what you get is a 0..0 which isn't allowed. There are 2 methods which you can use to remedy the situation. remove the virtual option from either one side or both sides of the navigation properties, allowing for a 0..1 or a 1..1 map. explicitly add a property for the Foreign key from the other entity on each object. i.e. on class Region add a property for FactoryId and

Categories : Entity Framework



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.