EF Feature CTP5: Fluent API Samples
The information in this post is out of date.
Visit msdn.com/data/ef for the latest information on current and past releases of EF.
For Mapping with the Fluent API see https://msdn.com/data/jj591617
For Configuring Relationships with the Fluent API see https://msdn.com/data/jj591620
We have released Entity Framework Feature Community Technology Preview 5 (CTP5) . Feature CTP5 contains a preview of new features that we are planning to release as a stand-alone package in Q1 of 2011 and would like to get your feedback on. Feature CTP5 builds on top of the existing Entity Framework 4 (EF4) functionality that shipped with .NET Framework 4.0 and Visual Studio 2010 and is an evolution of our previous CTPs.
Code First provides a Fluent API that can be used to further configure a model, this post will provide a series of short samples of using the Fluent API.
NOTE: The Fluent API is a more advanced concept and this post assumes you have an understanding of the concepts detailed in the Code First Into.
The Model
The samples shown in this post all make use of the following model:
public class ProductContext : DbContext
{
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<Tag> Tags { get; set; }
public DbSet<Person> People { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<OrderLine> OrderLines { get; set; }
public DbSet<OrderLineNote> OrderLineNotes { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// TODO: Use Fluent API Here
}
}
public class Category
{
public string CategoryCode { get; set; }
public string Name { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public string PrimaryCategoryCode { get; set; }
public virtual Category PrimaryCategory { get; set; }
public string SecondaryCategoryCode { get; set; }
public virtual Category SecondaryCategory { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
}
public class DiscontinuedProduct : Product
{
public DateTime DiscontinuedDate { get; set; }
}
public class Tag
{
public string TagId { get; set; }
public virtual ICollection<Product> Products{ get; set; }
}
public class Person
{
public int PersonId { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
public ICollection<Order> Orders { get; set; }
}
public class Address
{
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
}
public class Order
{
public int OrderId { get; set; }
public DateTime OrderDate { get; set; }
public ICollection<OrderLine> Lines { get; set; }
public Person Person { get; set; }
}
public class OrderLine
{
public int OrderId { get; set; }
public int ProductId { get; set; }
public int Quantity { get; set; }
public Product Product { get; set; }
public ICollection<OrderLineNote> Notes { get; set; }
}
public class OrderLineNote
{
public int OrderId { get; set; }
public int ProductId { get; set; }
public string Note { get; set; }
public OrderLine OrderLine { get; set; }
}
Primary Keys
Simple primary key:
modelBuilder.Entity<Category>()
.HasKey(c => c.CategoryCode);
Composite primary key:
modelBuilder.Entity<OrderLine>()
.HasKey(l => new { l.OrderId, l.ProductId });
Properties
Make a clr-nullable property required:
modelBuilder.Entity<Product>()
.Property(p => p.Name)
.IsRequired();
Change string length:
modelBuilder.Entity<Product>()
.Property(p => p.Name)
.HasMaxLength(50);
Switch off Identity:
modelBuilder.Entity<Product>()
.Property(p => p.ProductId)
.HasDatabaseGenerationOption(DatabaseGenerationOption.None);
Ignore a property:
modelBuilder.Entity<Person>()
.Ignore(p => p.Name);
Types
Specify a type is a complex type:
modelBuilder.ComplexType<Address>();
Ignore a type:
modelBuilder.Ignore<Person>();
Relationships
Standard one to many:
modelBuilder.Entity<Product>()
.HasRequired(p => p.PrimaryCategory)
.WithMany(c => c.Products)
.HasForeignKey(p => p.PrimaryCategoryCode);
The same relationship can also be configured from the other end (this has the same effect as the above code):
modelBuilder.Entity<Category>()
.HasMany(c => c.Products)
.WithRequired(p => p.PrimaryCategory)
.HasForeignKey(p => p.PrimaryCategoryCode);
Relationship with only one navigation property:
modelBuilder.Entity<OrderLine>()
.HasRequired(l => l.Product)
.WithMany()
.HasForeignKey(l => l.ProductId);
Switch cascade delete off:
modelBuilder.Entity<Category>()
.HasMany(c => c.Products)
.WithRequired(p => p.PrimaryCategory)
.HasForeignKey(p => p.PrimaryCategoryCode)
.WillCascadeOnDelete(false);
Relationship with composite foreign key:
modelBuilder.Entity<OrderLineNote>()
.HasRequired(n => n.OrderLine)
.WithMany(l => l.Notes)
.HasForeignKey(n => new { n.OrderId, n.ProductId });
Rename foreign key not exposed in object model:
modelBuilder.Entity<Order>()
.HasRequired(o => o.Person)
.WithMany(p => p.Orders)
.IsIndependent()
.Map(m => m.MapKey(p => p.PersonId, "CustomFkToPersonId"));
Rename columns in many:many table:
modelBuilder.Entity<Product>()
.HasMany(p => p.Tags).WithMany(t => t.Products)
.Map(m =>
{
m.MapLeftKey(p => p.ProductId, "CustomFkToProductId");
m.MapRightKey(t => t.TagId, "CustomFkToTagId");
});
Table & Column Mapping
Change column name:
modelBuilder.Entity<Category>()
.Property(c => c.Name)
.HasColumnName("cat_name");
Change table name:
modelBuilder.Entity<Category>()
.ToTable("MyCategories");
Change table name with schema:
modelBuilder.Entity<Category>()
.ToTable("MyCategories", "sales");
Inheritance Table Mapping
Table Per Hierarchy (TPH)
TPH = “Store all my data in one table and use the values from one or more columns to identify which type each row is”
Simple TPH is the default mapping for an inheritance hierarchy.
TPH with custom discriminator column name and values:
modelBuilder.Entity<Product>()
.Map<Product>(m => m.Requires("Type").HasValue("Current"))
.Map<DiscontinuedProduct>(m => m.Requires("Type").HasValue("Old"));
Table Per Type (TPT)
TPT = “store all the data for properties on the base type in a single table, store any additional data for derived types in an extra table that has a foreign key to the base table”
modelBuilder.Entity<Product>().ToTable("Products");
modelBuilder.Entity<DiscontinuedProduct>().ToTable("OldProducts");
Table Per Concrete Class (TPC)
TPC = “Create a completely separate table for each non-abstract type in my hierarchy”
modelBuilder.Entity<Product>().ToTable("Products");
modelBuilder.Entity<DiscontinuedProduct>()
.Map(m =>
{
m.MapInheritedProperties();
m.ToTable("OldProducts");
});
Summary
In this post we looked at a number of samples for the Code First Fluent API, any scenarios that are commonly asked about in our forum will be added to this post over time.
Feedback & Support
As always we would love to hear any feedback you have on the Fluent API by commenting on this blog post.
For support please use the Entity Framework Pre-Release Forum.
Rowan Miller
Program Manager
ADO.NET Entity Framework
Comments
Anonymous
December 07, 2010
What happened to EntityConfiguration<T> ???Anonymous
December 07, 2010
Seems the syntax has changed for Many to Many using .Map.... How about an example or docs on how to use them now?Anonymous
December 07, 2010
@Paul: EntityConfiguration<T> got renamed to EntityTypeConfiguration<T>.Anonymous
December 07, 2010
@Many to Many: Here is a simple example: modelBuilder.Entity<Movie>().HasMany(m => m.Actors).WithMany(a => a.Movies);Anonymous
December 07, 2010
@divega Need to use map as all my PK's are named Id. Will this work: HasMany(x => x.SitesFollowing).WithMany(z => z.UserFollowers).Map(y => { y.MapLeftKey((x => x.Id), "User_Id"); y.MapRightKey((x => x.Id), "Site_Id"); });Anonymous
December 07, 2010
@Paul, Yes, this is the right way to configure the mapping of a many-to-many association. That said, having the same key property name in both entities shouldn't be a problem. The default mapping convention should be creating SiteId and UserId columns and you shouldn't need to configure the mapping explicitly. Please, let me know if this is not working for you as expected. Thanks, DiegoAnonymous
December 07, 2010
I have following model: public class StudentGroup { public int Id { get; set; } public string Name { get; set; } } public class Student { public int Id { get; set; } public string FullName { get; set; } public virtual StudentGroup Group { get; set; } } I need to map to custom database schema: builder.Entity<StudentGroup>().ToTable("StudentGroups", "std"); builder.Entity<Student>().ToTable("Students", "std"); Table Students has FK column GroupId. I expect, that this should work by convention, but get exception, that there is no "StudentGroupId" column. Is the default convention [TypeName][Key]? I expect [PropertyName][Key]. If so, how to deal with two or more properties of the same type? How to map reference properties to column names explicitly like with MapSingleType and anonymous type in CTP4?Anonymous
December 07, 2010
Looking great Rowan. Large build is coming along well with CTP4 and I'm loving the ability to cusomise where needed or let convention do it when not needed. Time to upgrade for the new mapping features I think.Anonymous
December 07, 2010
Any plans for more providers ? SQLite, SQLCE, Oracle etc ? Will this use default mappings ? Will it recognize unlimited size strings?Anonymous
December 08, 2010
Any idea on how to go about "one to one" relationship using Fluent API? similar to "only one navigation property" sample above, but...
- that doesn't work if you want to tie 2 pk-s together (multiplicity error),
- annotations work - but introduce problems exactly in those complex cases where you need this (EF gets confused, something like referencing 2 rows in the same table),
- TPT inheritance does similar thing, I know - but introduces performance issues (unions for all 'types', when just querying on the 'base' class), exactly the reason why I'd need 1-to-1 worked out 'manually' (fluent API) you can find full story here: social.msdn.microsoft.com/.../b8850865-8fd6-41b5-9803-abf8e27039bb thanks!
Anonymous
December 08, 2010
hey guys did you add enumeration support?Anonymous
December 08, 2010
Nice work. just tried it out and it worked like a charm. Since I do model centric development this is a real time-saver. Many thanks to all the people.Anonymous
December 08, 2010
The comment has been removedAnonymous
December 08, 2010
Testing out to see if .WithRequiredDependent() does what I need.Anonymous
December 08, 2010
think about this scenario: public class User{ public int UserId{get;set;} public string UserName{get;set;} public virtual ICollection<User> Followers{get;set;} public virtual ICollection<User> Following{get;set;} } I do follows: modelBuilder.Entity<User>() .HasMany(b => b.Followers).WithMany(s => s.Following) .Map( y => { y.MapLeftKey(l => l.UserId, "BroadcasterId"); y.MapRightKey(r => r.UserId, "SubscriberId"); } ); I got "Sequence contains more than one matching element" exception.Anonymous
December 08, 2010
Here is discussion of my question social.msdn.microsoft.com/.../4fdb8f8a-fa5d-4d09-9ba0-205507a6969dAnonymous
December 08, 2010
The comment has been removedAnonymous
December 08, 2010
Thank you! This was exactly what I was looking for. social.msdn.microsoft.com/.../4fdb8f8a-fa5d-4d09-9ba0-205507a6969d Has anyone figured out a way to control the generation of the PK names/constraint names in the DB side ? My DBAs are not big fans of PK names that contain any form of Guid/auto naming sequence.Anonymous
December 09, 2010
I am trying to do TPH in Vb, I get Expression does not produce a value, will not complie modelBuilder.Entity(Of Product).Map(Of Product)(Function(m) m.Requires("Type").HasValue("Current")).Map(Of DiscontinuedProduct)(Function(m) m.Requires("Type").HasValue("Old")) What is wrong?Anonymous
December 09, 2010
@Paul I’ve added a couple of samples for renaming foreign key columns that are not exposed in the object model (including many to many) @Vesel The default in CTP5 is [TypeName][KeyName] and column names will be made unique by appending numbers. We are looking at swapping to [PropertyName][KeyName] for RTM but haven’t locked on what we will do yet. @Roland Code First uses the same provider as the rest of EF, which is public so third parties can build providers. SQL CE supports database generation in the latest CTPs of the 4.0 provider. We don’t have any plans to build any other providers aside from SqlClient and SQL CE. I’m not sure what you mean by default mappings, can you provide a little more info? You can affect the data type of the underlying column which will impact how big the string can be
- You can set the store type to be the max available characters (equates to nvarcahr(max) in SQL Server); modelBuilder.Entity<Product>().Property(p => p.Name).IsMaxLength();
- Or choose to use a text column in SQL Server; modelBuilder.Entity<Product>().Property(p => p.Name).HasColumnType("text"); @nsgaga We’ll keep working through your requirements on the forum thread @Kyle Bailey Enum support is not included in CTP5. We are working on Enum support at the moment but it requires changes to the core Entity Framework assembly and CTP5 purely adds on top of existing the existing assembly. We’ll let you know our plans around previews of enum support once we get a little further along with the work.
Anonymous
December 09, 2010
The comment has been removedAnonymous
December 09, 2010
Why are you making all methods which is public for generic EntityTypeConfiguration (and all related stuff) as internal for non generic version? as example why i need it: now i'm developing simple wcf crud service so i don't want to have crud operation methods for each entity type in my solution just to use generics. I'd like to use non generic version because it is easier in my case. But it takes more and more tricky to do the things which is easy for generic ones. Could you please at least change the modifier from internal to public in new version?..Or may be it will be possible for you to make non generic items as functional as generic ones? I don't think that method like this is the good one :) protected override void OnModelCreating(ModelBuilder modelBuilder) { if (haveToConfigureTypes.Count > 0) { for (int i = 0; i < haveToConfigureTypes.Count; i ) { EntityTypeConfiguration cfg = entityConfigurationMethod.MakeGenericMethod(new Type[] { haveToConfigureTypes[i] }).Invoke(modelBuilder, null) as EntityTypeConfiguration; } } base.OnModelCreating(modelBuilder); } I'm filling List<Type> with types before calling any method on DbContext and when DbContext wants to create model i have to fill the model builder with default configurations for this types. And all of this because DbContext can't add default configuration if there is no overrides for OnModelCreating method. So after overriding this method i have another problem with ModelBuilder because it has no method .Entity(Type entityType). Only Entity<T>(). thanks in advance.Anonymous
December 09, 2010
Hi there, How can update existing table in database from model? ex : I have a table that created from a model name "Person" with 2 fields: "PersonID" and "Name" now I want to add another fields to this model like "Email" how can do this without deleting my existing table and inner data ?Anonymous
December 09, 2010
Problem with TPT configuration in CTP5 tables : BaseEvent (PK bev_ID uniqueidentifier, bev_Name varchar(50)) Event (PK ev_bev_ID uniqueidentifier , ev_Date datetime) , FK from ev_bev_ID to bev_ID classes: public class BaseEvent{ public Guid ID {get;set;} public string Name {get;set;}} public class Event:BaseEvent{ public DateTime Date {get;set;} } in CTP4 all was fine with next configuration for modelBuilder: builder.Entity<BaseEvent>().HasKey(x => new {x.ID}) .MapHierarchy(x=>new{bev_ID=x.ID,bev_Name=x.Name}).ToTable("BaseEvent"); builder.Entity<Event>() .MapHierarchy(x=>new{ev_Date=x.Date,ev_bev_ID=x.ID}).ToTable("Event"); How can i write such configuration in in CTP5 ?Anonymous
December 10, 2010
How to create a one to one relationship using CTP 5 ? Please provide an example. Thx.Anonymous
December 12, 2010
@ Janosh The majority of the methods on the fluent API are generic to provide strongly typed access. From looking at scenarios people have reported from prior Code First CTPs, it seemed that the primary configuration scenarios were:
- Configuring a specific type (where the generics could be used)
- Configuring a pattern of changes where you'd want to customize thigns via a custom convention (which we added in CTP5). There were also a few cases where people wanetd to use Type and PropertyInfo directly t oregister specific types, ut we chose to focus on those top two scenarios which is why our configuration APIs are generic. That being said, part of the "custom convention" scenario may require you to register a bunch of types you want to include in your model and doing the MakeGenericMethod thing isn't a good solution so I do appreciate your feedback here. Registering a set of "Type"'s would be the thing we could add to the API.
Anonymous
December 12, 2010
The comment has been removedAnonymous
December 12, 2010
@AlexZ In CTP5, the MapSingleType and MapHierarchy methods were replaced by a single Map method and the ability to rename columns and tables directly. This is the code you'd need to do to use TPT and do the column name changes you had above: public class MyContext : DbContext { public DbSet<BaseEvent> BaseEvents { get; set; } public DbSet<Event> Events { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<BaseEvent>() .Property(b => b.ID).HasColumnName("bev_ID"); modelBuilder.Entity<BaseEvent>() .Property(b => b.Name).HasColumnName("bev_Name"); modelBuilder.Entity<BaseEvent>() .ToTable("BaseEvent"); modelBuilder.Entity<Event>() .Property(b => b.Date).HasColumnName("ev_Date"); modelBuilder.Entity<Event>() .ToTable("Event"); } } I wrote a blog post on mapping changes in CTP5 that you may want to check out: blogs.msdn.com/.../code-first-mapping-changes-in-ctp5.aspx Also, with the HasColumnName overloads, we realize you can no longer do this in bluk like you used to be able to do and we are working on improving this for the RTM release.Anonymous
December 12, 2010
@Nuno Here is an example of a one-to-one (required to required) mapping: public class Product { public int Id { get; set; } public string Name { get; set; } public ProductDetail ProductDetail { get; set; } } public class ProductDetail { public int Id { get; set; } public string Info { get; set; } public Product Product { get; set; } } public class MyContext : DbContext { public DbSet<Product> Products { get; set; } public DbSet<ProductDetail> ProductDetails { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Product>() .HasRequired(p => p.ProductDetail) .WithRequiredPrincipal(d => d.Product); } } In this case, the WithRequiredPrincipal call says the Product calss is the principal end of the relationship and the ProductDetail is the dependent end of the relationship and so that table will have the foreign key. If you look at the database for this, you'll see that ProductDetail.Id is the both the primary key for the ProductDetails table and a foreign key to Product.Id.Anonymous
December 13, 2010
Are you planning on adding support for constructor based initialization instead of using public getters/setters? Instead of: public class Order { public int OrderId { get; set; } public DateTime OrderDate { get; set; } } I'd like to see something like this... public class Order { int _orderId; DateTime _orderDate; public Order(int orderId, DateTime orderDate) { _orderId = orderId; _orderDate = orderDate; } } ...allowing you to properly encapsulate data. The mapping would have to be changed of course. Perhaps instead of mapping the property names you'd map the parameter names of the constructor? That would help a lot, since it's a nightmare to have all these "domain" objects leaking their innards.Anonymous
December 13, 2010
Suppose I have the following base classes: Order and OrderLine. Now I also have the following concrete types: IncomingOrder, OutgoingOrder, IncomingOrderLine, OutgoingOrderLine. In the Order base class I have defined the following: public virtual void ICollection<OrderLine> OrderLines { get; set;} Couple of questions about this set up:
- Is it right to have the OrderLines property in the Order base class?
- If it is, how do I indicate that IncomingOrder uses IncomingOrderLine?
- OrderLine base class has a property named OrderDate. How do I indicate that for IncomingOrderLine the column name is "ReceiveDate"? Hopefully this makes sense. I will try to clarify if needed. We basically have a schema that defines two remarkably similar objects (and child objects) and I'd like to create a model that allows the developer to work with them pretty much interchangably. By providing common property names and such.
- Anonymous
December 13, 2010
Suppose I have the following base classes: Order and OrderLine. Now I also have the following concrete types: IncomingOrder, OutgoingOrder, IncomingOrderLine, OutgoingOrderLine. In the Order base class I have defined the following: public virtual void ICollection<OrderLine> OrderLines { get; set;} Couple of questions about this set up:
- Is it right to have the OrderLines property in the Order base class?
- If it is, how do I indicate that IncomingOrder uses IncomingOrderLine?
- OrderLine base class has a property named OrderDate. How do I indicate that for IncomingOrderLine the column name is "ReceiveDate"? Hopefully this makes sense. I will try to clarify if needed. We basically have a schema that defines two remarkably similar objects (and child objects) and I'd like to create a model that allows the developer to work with them pretty much interchangably. By providing common property names and such.
Anonymous
December 20, 2010
Can I USe Conventions + Fluent? I'm having a problem... I Have a class Person with an Address property, and a Name Property, and the Id I put [Required] on Name but not on Address. Address is a complex type, but the int field of address (House Number) is not null, when the database is created by the EF, How can I solve this?Anonymous
December 21, 2010
Using almost all of the mapping described above I get a ModelValidationException: EntityType 'OrderLineNote' has no key defined. Define the key for this EntityType. I amusing the 'Relationship with composite foreign key' above modelBuilder.Entity<OrderLineNote>() .HasRequired(n => n.OrderLine) .WithMany(l => l.Notes) .HasForeignKey(n => new { n.OrderId, n.ProductId }); Am I missing something else?Anonymous
December 21, 2010
I've attempted to draw a UML class diagram for the above model: yuml.me/.../ef-feature-ctp5-fluent-api-samples.aspx,%20%5Bnote:%20Model%20from%20EF%20Feature%20CTP5:%20Fluent%20API%20Samples%20%7Bbg:cornsilk%7D%5D,%20%5BPerson%7CName%5D-0..1%3E%5BAddress%7CStreet;City;State;Zip%5D,%20%5BPerson%5D-Orders%3E%5BOrder%7COrderDate%7Bbg:orange%7D%5D,%20%5BOrder%5D++-Lines%3E%5BOrderLine%7CQuantity%5D,%20%5BOrderLine%5D-1%3E%5BPerson%5D,%20%5BOrderLine%5D-1%3E%5BProduct%5D,%20%5BOrderLine%5D++-Notes*%3E%5BOrderLineNote%5D,%20%5BProduct%5D-%20PrimaryCategory%20%3E%5BCategory%5D,%20%5BProduct%5D-%20SecondaryCategory%20%3E%5BCategory%5D,%20%5BProduct%5D-Tags%20*%3E%5BTag%5D,%20%5BCategory%5D-Products%20*%3E%5BProduct%5D Would you agree that I've accurately reflected your intended model?Anonymous
December 22, 2010
Heres' a friendlier URL for the above comment: http://yuml.me/7dc1a1bbAnonymous
December 28, 2010
I have a situation similar to shichao with a many-many on a single type. I see that this is a known bug in CTP5 and should be fixed in the future. However, I'm wondering if there is a workaround or an alternative way to achieve this? Otherwise my current project is basically dead in the water until the next release.Anonymous
December 29, 2010
I have a situation similar to the product and category classes where there is a primary and secondary one to many on to the same table (Category)/ Can you show me the API I need to write to establish those two one to many relationships as i cannot get this to work without getting exceptions. If i just do the primary then that is fine. The only difference between your scenario and mine is that i use an int rather than a string.Anonymous
December 30, 2010
I have the same question with Rohan CraggAnonymous
January 04, 2011
@Price, This is something that would need changes to the core EF library and is something we intend to enable in a future release of EF. Thanks, ArthurAnonymous
January 04, 2011
@David Martin, I’m assuming some things based on your description but I think the answers to your questions are:
- This is a valid choice
- You will not have static typing for this in your model. However, assuming the mapping is setup correctly and the database contents matches the mapping you should get the correct runtime type.
- I believe you will need to expose the property on IncomingOrderLine and then map the name using HasColumnName in the normal way. Thanks, Arthur
Anonymous
January 04, 2011
@David Anderson Yes you can use conventions and the fluent API. The first thing to note about complex types is that (except in a few limited situations) the value of a complex property can never be null. It we generally always be an instance of the complex type even if all properties of the instance are null. Given that, for the complex type you will need to specify the nullability for each of the properties of the type. By default each property will be “null” or “not null” in the database based on the nullability of the CLR type. So if you want to make House Number “null” in the database you can make it a nullable int in your Address type: public int? HouseNumber { get; set; } If you want to keep the CLR type nullable but make the database column nullable, then you could do this: modelBuilder.ComplexType<Address>().Property(c => c.HouseNumber).IsOptional(); Note that you will have to be careful with this since there is now a mismatch between what can be stored in the database and what can be represented by the CLR type. Thanks, ArthurAnonymous
January 04, 2011
@Rohan Cragg As well as specifying the relationship you also need to configure the primary key for OrderLineNote. See the Primary Keys section above which has this snippet: modelBuilder.Entity<OrderLine>().HasKey(l => new { l.OrderId, l.ProductId }); Thanks, ArthurAnonymous
January 04, 2011
@Alex Peachey You should be able to specify a many-to-many on a single type if you are okay with the column names that are generated by default for the join table. However, if you need to specify different column names in the join table then I don’t think there is currently a workaround. We will certainly fix this bug. Thanks, ArthurAnonymous
January 04, 2011
@MrMark, I don’t fully understand what mapping you are trying to achieve. Could you post some more details of the classes and the relationships/foregign keys you need to map? It might be easier to post a question on the ADO.NET Entity Framework and LINQ to Entities (Pre-Release) MSDN forum since it is easier to create a thread there that we can use to drill down into the issue. The forum address is: social.msdn.microsoft.com/.../threads. Thanks, ArthurAnonymous
January 04, 2011
The comment has been removedAnonymous
January 06, 2011
I am not able to do modelBuilder.Entity<Person>().Ignore(p => p.Name); Ignore does not seem to be an option???Anonymous
January 11, 2011
How can I define the releationship table name this.HasMany(u => u.Permissions) .WithMany(p => p.Roles) .Map(m => { m.MapLeftKey(p => p.RoleId, "RoleID"); m.MapRightKey(p => p.PermissionId, "PermissionId"); }); how to do itAnonymous
January 19, 2011
How do I rename columns many to many table with composite keys?Anonymous
January 19, 2011
How to I map a many to many relation using a composite key? For simple types I have .HasKey(), but that won't work in this case. modelBuilder.Entity() .HasMany(i => i.Categories) .WithMany(o => o.Items) .Map( mc => { mc.ToTable("ItemCategories"); mc.MapLeftKey(i => i.Id, "ItemId"); mc.MapRightKey(o => o.TemplateID, "TemplateId"); mc.MapRightKey(o => o.ItemId, "ItemId"); } ); This is even a special case, where there is a simple key on one end of the many-many relation, and a composite one on the other end.Anonymous
January 20, 2011
How do I define a FK as non nullable when there's no property in the model? Ex: modelBuilder.Entity<Parent>().HasMany<Child>(x => x.Children) Where the class Child has no property called ParentId OR Parent? The FK field ParentId is generated in the db and it works, but is defined as 'int null'. It needs to be not null.Anonymous
January 20, 2011
I was able to map a many-to-many relationship with a composite key in some cases. But, the configuration is throwing an exception whenever the many-to-many is referencing the same table. The exception is "Sequence contains more than one matching element".Anonymous
January 22, 2011
How to use the Enum type on the property?Anonymous
January 26, 2011
hey! I'm haveing a troublesome scenario and perhaps anyone can shine some light on it. A user belongs to an office public virtual Office Office { get; set; } but and office has a contactperson public virtual User ContactPerson { get; set; } and i end up having OfficeId and OfficeId1 in user table and Userid in office table. What is the correct way to solve such a relationship? Thanks in advanceAnonymous
January 31, 2011
Hi Rowan, please do a blog post on Data Annotation feature showing one to one, one to many and many to many relationships. Currently there is no content on data annotation features of ctp5....its ctp4 content all over the internet....please provide some content for ctp5 Thanks !!Anonymous
February 07, 2011
So, it seems we're getting away from the "Database Designer Panels". Will we need to hand-code all of our Database/Context layouts going forward? I don't see how this is a productivity gain.Anonymous
February 15, 2011
Do you have any vb.net examples struggling with Relationship with composite foreign key.Anonymous
February 15, 2011
Is there a feature built in to easily avoid the use of Magic-Strings for table names within the table-per-type fluent mapping? For example: modelBuilder.Entity<Product>().ToTable("Products"); modelBuilder.Entity<DiscontinuedProduct>().ToTable("OldProducts"); Can I rely on exist logic to pluralize for me?Anonymous
February 22, 2011
In EF designer we can define conditions in mapping details. For example we can say that only entities with IsDeleted = false are mapped. Is this possible with EF CTP5 Fluent API?Anonymous
April 05, 2011
just wondering is there any download-able for the above sample?Anonymous
April 23, 2011
Hi, Can you tell me where [Fluent API Samples] Database schemaAnonymous
August 02, 2011
I think... ProductContext.Database.Create(); thinks!Anonymous
September 19, 2011
Here you find a fluent API for the SharePoint. FluentSP implements a modern fluent interface around the classic SharePoint 2010 API: www.parago.de/.../fluentsp-the-fluent-sharepoint-apiAnonymous
February 16, 2012
The comment has been removedAnonymous
March 21, 2013
I want have such class structure with Table per Concrete Type (each non anstract class in seperate table with all include inherited field) public abstract class BillingDetailBase { public Int32 Id { get; set; } } public abstract class BillingDetail : BillingDetailBase { public string Owner { get; set; } } public class User { public int UserId { get; set; } public virtual BillingDetailBase BillingDetail { get; set; } } public class BankAccount : BillingDetail { public string BankName { get; set; } public string Swift { get; set; } } public class CreditCard : BillingDetail { public int CardType { get; set; } public string ExpiryMonth { get; set; } public string ExpiryYear { get; set; } } I get error (23,6) : error 0040: Type BillingDetailBase is not defined in namespace CodeFirstDatabaseSchema (Alias=Self). (41,8) : error 0100: The referenced EntitySet BillingDetailBase for End BillingDetailBase could not be found in the containing EntityContainer. How I could solve problem?Anonymous
March 22, 2013
@Table per Concrete Type many abstract classes and point to base I've confirmed that this is a bug and I've opened a new issue to track it - entityframework.codeplex.com/.../981 It looks like the issue appears when you have two abstract base classes before your first concrete class. ~RowanAnonymous
August 21, 2014
How can I specify an Inverse Property for an Entity via fluent api. For eg: Party{ [InverseProperty("Party")] public ICollection<contract> ContractParty { get; set; } } Anyone can help how to set this via fluent apiAnonymous
August 22, 2014
@Vishnu VG - There are examples of how to configure relationships with the Fluent API here - msdn.microsoft.com/.../jj591620