Entity Framework CTP5 - Code First - Nested Query Error
Jan 3, 2011
I have the following classes:
public class Category
{
public int CategoryId { get; set; }
public string Name { get; set; }
}
public partial class CategoryMap : EntityTypeConfiguration<Category>
{
public CategoryMap()
{
this.HasKey(c => c.CategoryId);
this.Property(c => c.Name).IsRequired().HasMaxLength(400);
}
}
public class MyObjectContext : DbContext
{
public MyObjectContext(string connectionStringName)
: base(connectionStringName)
{
}
public DbSet<Category> Categories { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new CategoryMap());
base.OnModelCreating(modelBuilder);
}
}
Now when I run the following code I get an exception (GenericArguments[0], 'System.Int32', on 'System.Data.Entity.Internal.Linq.ReplacementDbQueryWrapper`1[TEntity]' violates the constraint of type 'TEntity')
DbDatabase.SetInitializer<MyObjectContext>(new DropCreateDatabaseIfModelChanges<MyObjectContext>());
using (var context = new MyObjectContext("NopSqlConnection"))
{
var query1 = from c in context.Categories
select c.CategoryId;
var test1 = query1.ToList(); //works fine
var query2 = from c in context.Categories
where query1.Contains(c.CategoryId)
orderby c.Name descending
select c;
var test2 = query2.ToList(); //throws the exception
}
Im a fan of the EF code first and with its last preview of the CTP5 I wonder if it would be safe for me to use this for a smaller site for customer? I would love to get your opinions on this? And any good sources for tutorials and information would be sweet. I'm currently reading the post on scottgu's blog about it.
But it creates the relationship (and the third mapping table) with cascade delete switched off by default. How can I tell EF to create the relationship with cascade delete switched on when using many-to-many?
I have a problem with strange generate sql in ef4 ctp5. I have simple model with mapping :
[Table("post_auction")] public class PostAuction { [Key,Column(Name="Id"),DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGenerationOption.Identity)] public int Id { get; set; } [Column(Name = "Number")] public int Number { get; set; } [Column(Name = "Label")] public string Label { get; set; } [Column(Name = "Description")] public string Description { get; set; } [Column(Name = "CategoryId")] public int PostAuctionCategoryId { get; set; } [Column(Name = "PriceCZK")] public int PriceCZK { get; set; } [NotMapped] public bool IsAuctionPhotoExitst { get { if (File.Exists(HttpContext.Current.Server.MapPath("~/Public/Images/Posts/Thumbs/small_" + this.Number + ".jpg"))) return true; return false; } } }
I have a web app for our golf club. When I compute handicap index for each golfer, I have to select the most recent scores and then a subset of those scores depending on how many rounds of golf the golfer has played. All the scores are entered into a single SQL Express table called "Rounds". Verbally, this is what I'm trying to do:
1) select the twenty most recent golf scores (sort on date descending, "take(20)") [if less than 20 records, then select all available];
2) for this set of records, select the 10 lowest scores (or smaller number if golfer has less than 20 rounds);
3) compute the average round differential for the subset of records, etc. to calculate handicap index (this step is working ok...)
My current VB code has this LINQ query (which is flawed -- it selects the lowest handicap differential scores of ALL records for the filtered user):
[Code]....
How do I modify this query to accomplish items 1) & 2) above? It seems this should be simple, but my experience with queries is still limited.
You can find the source code demonstrating this issue @ http://code.google.com/p/contactsctp5/
I have three model objects. Contact,ContactInfo,ContactInfoType. Where a contact has many contactinfo's and each contactinfo is a contactinfotype. Fairly simple I guess. The problem I'm running into is when I go to edit the contact object. I pulled it from my contact repository. Then I run "UpdateModel(contact);" and it updates the object with all the values from my form. (monitoring with debug) When I save the changes though, I get the following error:
The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.
It seems like after I call update model it nulls out my references and this seems to break everything?
Here are my models:
public partial class Contact { public Contact() { this.ContactInformation = new HashSet<ContactInformation>(); } public int ContactId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public virtual ICollection<ContactInformation> ContactInformation { get; set; } } public partial class ContactInformation { public int ContactInformationId { get; set; } public int ContactId { get; set; } public int ContactInfoTypeId { get; set; } public string Information { get; set; } public virtual Contact Contact { get; set; } public virtual ContactInfoType ContactInfoType { get; set; } } public partial class ContactInfoType { public ContactInfoType() { this.ContactInformation = new HashSet<ContactInformation>(); } public int ContactInfoTypeId { get; set; } public string Type { get; set; } public virtual ICollection<ContactInformation> ContactInformation { get; set; } }
I get an cast exception when i am trying to insert an entity in Entity Framework (using code-first). From this code :
public virtual T Insert(T entity) { return Context.Set<T>().Add(entity); }
The cast exception is like "impossible to cast ...Collection'1(Entity) to type (Entity)" I can't figure out why. I am pretty sure ive done everything right. Post entity
public class Post { public long PostId { get; private set; } public DateTime date { get; set; } [Required] public string Subject { get; set; } public User User { get; set; } public Category Category { get; set; } [Required] public string Body { get; set; } public virtual ICollection<Tag> Tags { get; private set; } public Post() { Category = new Category(); if (Tags == null) Tags = new Collection<Tag>(); }................................
I have 2 tables A and B that have a many to many relationship. I am using nested repeaters to show the data in a web page. My issue is, how do I write an ObjectQuery or an IQueryable query that returns the parent rows in A and the child rows in B so that I can use them as my data sources for my inner and out repeater. I have the code I wrote so far below but I am not sure if it is correct or even close.
Users Id Username Email Password UserStatuses Id Name Users_UserStatus Id User (FK - Users: Id) Status (FK - UserStatuses: Id) StatusDate
As you can see, UserStatuses is a reference table with various statuses. Users_UserStatus is a join table between Users and UserStatuses. Using Entity Framework, how can I do a conditional to check if the latest StatusDate is "Pending"? As of now, I have the following:
Best way to show the SQL trace of a LINQ query to Entity Framework 3.5? I am using ASP.net and EF 3.5.
Dim dbo As Web.Portal.RBMEntities = New Web.Portal.RBMEntities Dim Query = From RoleAllocations In dbo.RoleAllocations Where RoleAllocations.user_id = _ID And RoleAllocations.expire_date > Today Select RoleAllocations
I am new to this, and I am trying to implement a linq query similar to db.Genres.Include("Albums") command from
mvc music store using my current DB setup. I realize that the tutorial mentions Checlking the "Include foreign key columns in the method" when creating the tables in ADO.NET, but if I am using LINQ to SQL classes, then how can I obtain the same effect. And how do I use db.Genres.Include("Albums") to simplify my life?
I just tring to a complex (for me) with ado.net entity framework this is the structure: In practice it is a sort of group purchasing (Buyers) For each group of purchase (Buyer) should have the opportunity 'to select all products of the brands indicated in buyer I'm doing function to return correct data like this:
public List<Product> GetProductsByBuyer(int vBuyerId) { Buyersctx.Products.MergeOption = MergeOption.NoTracking; return (from lProduct in Buyersctx.Products.Include("Brand").Include("Buyers") where select lProduct).ToList(); }
I'm currently learning entity framework (from the Julia Lerman book "Programming Entity Framework") and got really confused at the grouping part.
var contacts = from c in context.Contacts group c by c.Title into myGroup select myGroup;
This is supposed to return a Grouping<K,T> type, but the book didn't give an example on how exactly do I access this "contacts" query and I can't figure it out. When I did foreach(var contact in contacts), my "contact' variable has no knowledge of any of the properties of the Contact type (contact.FirstName etc).
<EntitySet Name="EntityFramework" EntityType="SEOAnalysisModel.Store.EntityFramework"> <DefiningQuery> SELECT Keyword, ResultHead ,Year from SeoAnalysis where Year = 2005
I need to check if any rows are returned in a QueryString here's what I have so far.not sure what code to put to see if the row count is greater than 1
private void BindDataToGrid() { //MessageBoardEntities3 is ThemeableAttribute connection string name int TID = Convert.ToInt32(Request.QueryString["ThreadID"].ToString()); // if Post ID is int var context = new MessageBoardEntities3(); gvPosts.DataSource = from p in context.Posts where p.ThreadID == TID select new { p.Post1, p.PostID }; gvPosts.DataBind(); lblNoPosts.Text = "No posts found for this thread."; }
I have a good friend who owns a print shop and he has asked me to create him a simple online shop where he can take print orders. His print shop location is kind of hidden, and business isn't going well at the moment. This is why he wants to move online. I said I would do it for him, but it will take a while before he has anything to look at. Where I am most stuck is the Model. The problem with this sorts of shops is that each Product, depending on its category would have different attributes. How ? Here is an example: [URL] A user would choose a product category, then he/she would get to the following: [URL] Now he/she would click the Order link to order a certain qunatity. On the next page, depending on what category they are in, they'll get a form where they can choose order attributes. There aren't many attribues for BUSINESS CARDS. But if they had chosen CARBONLESS FORMS, they would get options to tweak like: Squencial Numbering to start from 103490Position of Numbering..etc
I asked for advice at the SQL Server forums, and finally I came up with something like this:[URL] But with that database design, I will have a lot of type casting to do for the attributes ! << In fact I'm not sure if that would be even possible. Then I watched this video, and the author does something cool ! she uses Inheritance. Then I started Wonding ... Is it possible for me to have a Parent [ Product ] class, and have its children entities with different (added) attributes?
I been looking but I cant find any info on this topic Anyway I got a model that looks like this.
[Code]....
I want to cascade delete a category with all its sub categories but I cant make that reference in the database, not with the option to cascade update or delete. It work fine with pagecontents and all the other I got its just this same table reference. In NHibernate I do the cascade setting hbm or with a better way using the fluent option. How do I go about this task now?
ive tried to build some base project with above technologies. I wanted maximum flexibility and testability so i tried to use patterns along the way to make this as a base for future projects. However, it seem.something is wrong or whatever and i really need help here. So
i have two questions :1- Is there anything wrong with my current code ? Ive applied patterns correctly ?
2- Why do this code actually connect to the database, create it, but doesnt support insert even if i perform the corrects operation ? (Look at the end of the post for details about this error)
I have two entities : Comment and Review
COMMENT [Code]....
REVIEW[Code].... I built up a base repository for each of them this way :GENERIC REPOSITORY[Code]...For specific operations, i use an interface :[Code]....So i am getting the generics operations from the abstract class plus the specific operations :[Code]....As you figured out, i also use a database factory will produce the database context :DATABASE FACTORY [Code]....DISPOSABLE (Some extensions methods...)[Code]....DATABASE [Code]....And to finish, i have my unit of work....UNIT OF WORK[Code]....I also binded using Ninject the interfaces :NINJECT CONTROLLER FACTORY [Code]....however, when i call in the constructor ...[Code]....
This seem to create the database but doesnt't insert anything in the database in EF4. It seem that i may figured out the problem.. while looking at the database object.. the connection state is closed and server version throw an exception of this kind :
ServerVersion = '(((System.Data.Entity.DbContext (_database)).Database.Connection).ServerVersion' threw an exception of type 'System.InvalidOperationException'
I am doing the right things ? Is there anything wrong in what ive built ? Also if you have recommandation about the code i posted, i would be glad. I am just trying to the learn the right way for building any kind of application in MVC 3. I want a good a start.
I use : - Entity Framework 4 Code-First CTP 5 - ASP.NET MVC 3 - Ninject as DI Container
Is there a way to export a EF 4.0 Data Model to EF 3.5?
I looked around and found that we are not able to access EF 4.0 from a ASP.Net 3.5 project here: [URL]
Our project is the 1st to go to .Net 4.0 using Entity Framework and we (the team) were wondering if there was a way for the other projects that "might" need to access our data that are still using the .Net 3.5 framework.
i have a web-site which uses forms based authentication. thus i have a login page with a login control on it. how would i go about coding the authenticate event of this control to talk to the Entity Framework to validate the user credentials?
When I use classical ADO.NET or (which is interesting) EntityDataSource (e.g. for GridView), then page load within 1 second.But when I use ic codefile code like:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Cty = CType(Request.QueryString("cty"), Integer) ' course type Page.SetFocus(ddl_FGPhotosOK) If Not IsPostBack Then ' read course status Using ctx_sdbEntities As New sdbEntities() [code]...
I've just created a new MVC 2 application that references both an entity model library and a services library, and all compiles fine without running the app, but when I try running it, I get the following runtime error"
Compiler Error Message: CS0012: The type 'System.Data.Objects.DataClasses.EntityObject' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
I have double checked umteen times (e.g. Umpteen*n) and the cited assembly is refenced in all three projects. If it wasn't, WTF would I not get a build error?