w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
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

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

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#

Model-First Entity Framework: using Enums or default values for Entity using Designer (.NET 4.0)
create a property with int value in your entity(that I call it status) in model designer set it setter and getter private create a partial class in your model namespace with same name of your entity name create a public Enumeration property in partial class(that I call it situation) in situation getter return your private property(status) in situation setter set value of private property(status)

Categories : Asp Net

Entity framework Explicit Loading multi-level
Try changing this line: listSubs = db.Subscribers.Include("Channel").Where(o => o.User.Username == username.ToLower() && o.Channel.IsActive && o.Channel.IsPublic && o.Channel.Posts.Count(p => p.PublishTime <= DateTime.Now && p.IsActive && p.IsHot) > 0); To also call .Include("Channel.Posts"): listSubs = db.Subscribers.Include("Channel").Include("Channel.Posts") .. etc;

Categories : Entity Framework

How do I do a multi-join on two SQL Views in an Entity Framework Model?
So to join you can use the join keyword then use on to specify the conditions. && (the logical and operator in C#) will be translated to the SQL AND keyword. Also, in EF they have what are known as "implicit joins" meaning if I have TableA with a foreign key to TableB, call it fKey. Doing where TableA.fKey == TableB.pKey will cause the provider to put a join there. To select you simply need to do; select new { prop1 = TableA.Prop1, prop2 = TableB.Prop1 } this will create a new anonymous which selects values from both tables. Below is a more complete example of the join syntax. I think it uses all of the things you asked about; var result = from a in TableA join b in TableB on a.fKey equals b.pKey && b.Status equals 1 select new { a.Prop1, a.P

Categories : C#

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#

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 filter DbContext in a multi-tenant application using Entity Framework with MVC4
I like your approach better than some of the other examples you've provided. Filtering based on the logged-in user should be the most effective way to make sure you're filtering your data appropriately assuming each tenant runs off the same codebase and domain. (If not, you could utilize those to filter as well.) If you're concerned about database performance with filtering tables that don't have a CompanyID you can purposely denormalize your database to include that field in those tables. The reflection approach you cited, although elegant, seems overly complicated and like a lot more overhead than including the CompanyID in your db call (especially since the db call is happening in both instances). EDIT (after comment): As for the rest of it, you seem to have written a lot of excess

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

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 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#

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#

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

Way to track number and type of objects deleted in entity framework
You can use the ChangeTracker property on the DbContext to find out what Entity Framework will do when SaveChanges is called. If you check it before you call SaveChanges you will get everything that Entity Framework is about to delete or modify. This assumes that it is indeed Entity Framework that does the cascading delete. It might also have been implemented as a cascade delete option on the foreign key in the database. In that case, it's the DB doing the deletes and not EF so the change tracker will not be aware of the pending deletions.

Categories : C#

.Execute not available on a type safe Entity Framework query (Include & where)
I have found it, maybe someone can comment if this is good practice or not? var query = this.Storage.Tubes.OfType<Preferred>() .Include(b => b.Order); return ((ObjectQuery<Preferred>)query).Execute(MergeOption.OverwriteChanges) .SingleOrDefault(cust => cust.Id == customerId && cust.CustomerType == (int)cusType);

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 complex type multiple instances in one model?
With EF 6, Code First will prefix the column names with your Property name when you use multiple instances of same complex type, like PersonalAddress_Street BusinessAddress_Street ... and so on. You only need the mappings older versions of EF. The mapping option also allows you to replace these autogenerated names with something nicer. Also, I don't think this is the correct configuration code based on your models (typo maybe?): this.Property(t => t.PersonalAddress.Address.Street) // should be this.Property(t => t.PersonalAddress.Street)

Categories : C#

AutoMapping an Enum to an Entity Framework 5.0 complex type error
If you have problmes with complex type mapping, you can implement manual mapping based on AutoMapper: Mapper.CreateMap<PatternDto, PatternModel>().ConvertUsing(pattern => { if(pattern == null) return new PatternModel(); return new PatternModel { EmailPattern = pattern.EmailPattern, SmsPattern = pattern.SmsPattern }; }); Good luck!

Categories : Entity Framework

'TypeLoadException: Could not load type' for Entity Framework databaseInitializer in web.config
You need to specify the type of the DropCreateDatabaseIfModelChanges as well: <databaseInitializer type="System.Data.Entity.DropCreateDatabaseIfModelChanges`1[[Domain.EVRMDBContext, EVRM]], EntityFramework" />

Categories : Entity Framework

ASP.NET MVC with Entity Framework - Update/Save complex type property
As you mentioned, the problem occurs when more than one quantity has same Unit. To avoid adding same unit multiple time you can check if a unit is already in the db. If it exists then reuse the existing unit. if (q.Id == 0) { var unit=db.Units.FirstOrDefault(u=>u.Id==q.Unit.Id); if(unit!=null) q.Unit=unit; db.Quantities.Add(q); }

Categories : C#

Load values from Entity Framework into textboxes
I think you need to learn the Entity framework. here you can learn by videos provided by team. sample code. using (var db = new BloggingContext()) { // Create and save a new Blog Console.Write("Enter a name for a new Blog: "); var name = Console.ReadLine(); var blog = new Blog { Name = name }; db.Blogs.Add(blog); db.SaveChanges(); // Display all Blogs from the database var query = from b in db.Blogs orderby b.Name select b; Console.WriteLine("All blogs in the database:"); foreach (var item in query) { Console.WriteLine(item.Name); } Console.WriteLine("Pres

Categories : Wpf

Entity Framework - Only update values that are not null
First off, you need to use something like this to select the entities you want to update: var widget = db.Widgets.First(p => p.ID == 1); var widget_diff = db.Widgets_Changes.First(p => p.ID == 1); Now you can simply use reflection to update all fields: foreach(var fromProp in typepf(Widget).GetProperties()) { var toProp = typeof(Widget_Change).GetProperty(fromProp.Name); var toValue = toProp.GetValue(widget_diff, null); if (toValue != null) { fromProp.SetValue(widget, toValue, null); } } This can be sped up a bit by building a list the of properties up front, so you only have to use reflection once: public static class WidgetUtil { public static readonly IEnumerable<Tuple<PropertyInfo, PropertyInfo>> PropertyMap; static Uti

Categories : C#

Entity Framework 5 foreign key values not updating (VB.NET)
I finally worked out what I was doing wrong, I did not check the box for "include foreign key relationships" when setting up the model, meaning the relationships were not properly defined (I assume).

Categories : Vb.Net

Using varying values in expressions in Entity Framework
If you don't need to do this using a single Expression, you could take advantage of let: IQueryable<Result> PerformSelect(IQueryable<Source> sources) { var foo = new Foo(); return from source in sources let tmp = foo.PropertyThatVaries select new Result { Id = source.Id + tmp, Prop = tmp }; } I think this will do what you want.

Categories : C#

Entity Framework Table Per Class/Type, Many To Many relationship between derived classes
This is now solved. It was a foreign-key mapping issue: modelBuilder.Entity<User>().HasMany<Role>(r => r.Roles).WithMany(u => u.Users);

Categories : Entity Framework

Using an array of enumeration values in a where clause with Entity Framework 5
Switching from Any() to Contains() got me part of the way there, but the final solution required using a List rather than a byte[]. Here is the final code that works: var statusArray = (new MyEntityStatus[]{MyEntityStatus.Status1, MyEntityStatus.Status2}).Cast<byte>().ToList(); var results = myDataContext.MyEntities..Where(e => statusArray.Contains((byte)e.Status)).ToArray(); Apparently, EF treats a List differently from byte[]. See: .NET Entity Framework - Using .Contains() to find a byte value in a Where expression

Categories : Entity Framework

Entity Framework, Multiple values 1 cell/ Datagridview c#
Is this winforms or wpf, or asp.net? I would start be creating a custom control that takes these two values, and displays your checkboxes. Then feeding the data into said control and putting that into your datagrid. I'm not sure if this is similar to your usecase but you might want to check this out, explaning how to get mulitple controls in a single datagridview cell. http://social.msdn.microsoft.com/Forums/windows/en-US/c28399bb-9d50-4a1e-b671-3dbaebb5cc69/multiple-controls-in-a-single-datagridview-cell This may not answer your question completely but might give you a head start

Categories : C#

Selecting changes in values with Lambda, Linq, Entity Framework
Edited after reading your dataset again. I see a grouping wouldn't work. Ideally though, you want this logic on the db server, not client side due to network io, etc. You can either write this as a proc or dynamic sql. Dynamic sql maybe easier in the near term. Simple method, select it into a cursor. Loop into a temp table variable and return the result set. If you dataset is really small, then stick with the easy to read linq loop you have. Don't add more complexity unless you need too. i.e. don't micro-optimize.

Categories : C#

Entity Framework Eager Loading Table-Per-Type Inheritance derived class
I don't see why ... var list = context.Trainings.Include(t => t.Persons) .Where(t => t.Name == someName) .ToList(); ... shouldn't work. EF should populate the Persons list with concrete Student and Instructor entities. You neither have a "one-to-zero-or-one relationship" nor is your navigation property (Training.Persons) "on the derived class". So, I think the mentioned limitation does not apply to your model and query.

Categories : Entity Framework

Entity Framework - default values doesn't set in sql server table
I think this answers your question (but I don't know, if this is the answer you wanna read): How can I set default values in Entity Framework

Categories : C#

C# entity framework storing values returns null exception
I have no idea what you think you're doing with these two statements, but it's probably not what you think it is. var id = from t in textBox.Text where t != null select textBox.ID; var text = from t in textBox.Text where t != null select t; Then your foreach statements really make no sense because you will only ever have one item in the collections. It seems like you're trying to only save the data if there is something in the textbox, for which you should probably just do a simple if statement. Next, you create new crossword objects in each foreach, but you only assign an id in one, and text in the other.. this is also probably not what you want. More than likely, you just want to do this: if (!string.IsNullOrEmpty(textbox.Text)) { Mod

Categories : C#

Entity Framework / Linq - Get distinct values of dynamically specified property
You might try something like this (similar to the post that was suggested as duplicate) public static class DynamicQuerier { private delegate IQueryable<TResult> QueryableMonad<TInput, TResult>(IQueryable<TInput> input, Expression<Func<TInput, TResult>> mapper); public static IQueryable<TResult> Select<TInput, TResult>(this IQueryable<TInput> input, string propertyName) { var property = typeof (TInput).GetProperty(propertyName); return CreateSelector<TInput, TResult>(input, property, Queryable.Select); } private static IQueryable<TResult> CreateSelector<TInput, TResult>(IQueryable<TInput> input, MemberInfo property, QueryableMonad<TInput, TResult> method) { var s

Categories : C#

Prevent Entity Framework from adding duplicated keys in migration with table per type inheritance
Try making both tables inherit from an abstract class as described here public abstract class ProductBase { [Key] public int ProductId { get; set; } } public class Product: ProductBase { public int Value { get; set; } } public class Service : ProductBase { public int OtherValue { get; set; } }

Categories : Entity Framework

Avoiding null or empty values to save in database using Entity Framework
You have several options to fulfill your requirements, two of them are Client Side validation and server side validations that means you need to validate the data before send it to database for saving.. like you have model classes right.. that represent your tables public class User { [Required] public string UserName{get; set;} ... ... } suppose if you try to send null values to controllers or dbcontext it wont allows you to insert null values into it since it allows only non-null values. and also you can do this as well using jquery function buttonClick() { if($('#txtName').val()=='') { alert('Please enter name'); return false; } else { //make ajax call here } } like this you can do it in many ways you can use unobtrusive javascript as well. Hope this helps

Categories : Asp Net Mvc

How to set default values for foreign keys in Entity Framework code-first models
Provide default status to order via constructor (otherwise new status will be inserted, because whole graph will be in Added state): public class Order { public int Id { get; set; } public string Name { get; set; } public virtual Status Status { get; set; } public Order(Status initialtStatus) { Status = initialtStatus; } } And use it like this: var status = db.Statuses.Find(1); var order = new Order (status) { Name = "Lazy" }; db.Orders.Add(order); db.SaveChanges(); UPDATE: Another option is attaching default status entity to context or setting it's state manually: var order = new Order { Name = "Lazy" }; db.Entry(order.Status).State = EntityState.Unchanged; // avoid inserting db.Orders.Add(order); db.SaveChanges();

Categories : Entity Framework



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