Quantcast
Channel: Entity Framework
Viewing all 10318 articles
Browse latest View live

Closed Issue: Query: Perf: Use of Nullable.HasValue in the body of a Linq query doesn't produce the expected parameters in the generated SQL [1575]

$
0
0
When a query includes the use of Nullable<T>.HasValue and Nullable<T>.Value in the query, the SQL that we are generating doesn't generate a bit parameter for the use of HasValue, instead we have a T typed parameter that duplicates the value of the nullable object.

Have a query with this shape:

```
int receiptIdFilter = 20;
int? topicIdFilter = null;
DateTime dateFilter = DateTime.Now;

var query = context.Receipts.Include(r => r.Publication)
.Where(r => r.DateInserted < dateFilter
&& r.ReceiptId > receiptIdFilter
&& r.Publication.TopicId == (topicIdFilter.HasValue ? topicIdFilter.Value : 0)
&& r.Publication.ReceiptCount > 1)
.OrderBy(r => r.ReceiptId)
.Skip(50)
.Take(25);
```

The generated SQL looks like this:

```
SELECT TOP (25)
[Project1].[ReceiptId] AS [ReceiptId],
[Project1].[PublicationId] AS [PublicationId],
[Project1].[DateInserted] AS [DateInserted],
[Project1].[PublicationId1] AS [PublicationId1],
[Project1].[TopicId] AS [TopicId],
[Project1].[ReceiptCount] AS [ReceiptCount],
[Project1].[Name] AS [Name],
[Project1].[DateInserted1] AS [DateInserted1]
FROM ( SELECT [Project1].[ReceiptId] AS [ReceiptId], [Project1].[PublicationId] AS [PublicationId], [Project1].[DateInserted] AS [DateInserted], [Project1].[PublicationId1] AS [PublicationId1], [Project1].[TopicId] AS [TopicId], [Project1].[ReceiptCount] AS [ReceiptCount], [Project1].[Name] AS [Name], [Project1].[DateInserted1] AS [DateInserted1], row_number() OVER (ORDER BY [Project1].[ReceiptId] ASC) AS [row_number]
FROM ( SELECT
[Extent1].[ReceiptId] AS [ReceiptId],
[Extent1].[PublicationId] AS [PublicationId],
[Extent1].[DateInserted] AS [DateInserted],
[Extent2].[PublicationId] AS [PublicationId1],
[Extent2].[TopicId] AS [TopicId],
[Extent2].[ReceiptCount] AS [ReceiptCount],
[Extent2].[Name] AS [Name],
[Extent2].[DateInserted] AS [DateInserted1]
FROM [dbo].[Receipts] AS [Extent1]
INNER JOIN [dbo].[Publications] AS [Extent2] ON [Extent1].[PublicationId] = [Extent2].[PublicationId]
WHERE ([Extent1].[DateInserted] < @p__linq__0) AND ([Extent1].[ReceiptId] > @p__linq__1) AND ((([Extent2].[TopicId] = (CASE WHEN (@p__linq__2 IS NOT NULL) THEN @p__linq__3 ELSE 0 END)) AND ( NOT ((1 = 0) OR (CASE WHEN (@p__linq__2 IS NOT NULL) THEN @p__linq__3 ELSE 0 END IS NULL)))) OR (1 = 0)) AND ([Extent2].[ReceiptCount] > 1)
) AS [Project1]
) AS [Project1]
WHERE [Project1].[row_number] > 50
ORDER BY [Project1].[ReceiptId] ASC

/*
DateTime p__linq__0 = 8/20/2013 1:52:46 PM
Int32 p__linq__1 = 20
Int32 p__linq__2 = 4
Int32 p__linq__3 = 4
*/
```

However, if we take the use of Nullable<T>.HasValue outside of the query, the parameters get the expected types.

Assume a query with this shape:
```
int receiptIdFilter = 20;
int? topicIdFilter = 4;
bool hasvalue = topicIdFilter.HasValue;
DateTime dateFilter = DateTime.Now;

var query = context.Receipts.Include(r => r.Publication)
.Where(r => r.DateInserted < dateFilter
&& r.ReceiptId > receiptIdFilter
&& r.Publication.TopicId == (hasvalue ? topicIdFilter.Value : 0)
&& r.Publication.ReceiptCount > 1)
.OrderBy(r => r.ReceiptId)
.Skip(50)
.Take(25);
```

The generated SQL will now look like this:
```
SELECT TOP (25)
[Project1].[ReceiptId] AS [ReceiptId],
[Project1].[PublicationId] AS [PublicationId],
[Project1].[DateInserted] AS [DateInserted],
[Project1].[PublicationId1] AS [PublicationId1],
[Project1].[TopicId] AS [TopicId],
[Project1].[ReceiptCount] AS [ReceiptCount],
[Project1].[Name] AS [Name],
[Project1].[DateInserted1] AS [DateInserted1]
FROM ( SELECT [Project1].[ReceiptId] AS [ReceiptId], [Project1].[PublicationId] AS [PublicationId], [Project1].[DateInserted] AS [DateInserted], [Project1].[PublicationId1] AS [PublicationId1], [Project1].[TopicId] AS [TopicId], [Project1].[ReceiptCount] AS [ReceiptCount], [Project1].[Name] AS [Name], [Project1].[DateInserted1] AS [DateInserted1], row_number() OVER (ORDER BY [Project1].[ReceiptId] ASC) AS [row_number]
FROM ( SELECT
[Extent1].[ReceiptId] AS [ReceiptId],
[Extent1].[PublicationId] AS [PublicationId],
[Extent1].[DateInserted] AS [DateInserted],
[Extent2].[PublicationId] AS [PublicationId1],
[Extent2].[TopicId] AS [TopicId],
[Extent2].[ReceiptCount] AS [ReceiptCount],
[Extent2].[Name] AS [Name],
[Extent2].[DateInserted] AS [DateInserted1]
FROM [dbo].[Receipts] AS [Extent1]
INNER JOIN [dbo].[Publications] AS [Extent2] ON [Extent1].[PublicationId] = [Extent2].[PublicationId]
WHERE ([Extent1].[DateInserted] < @p__linq__0) AND ([Extent1].[ReceiptId] > @p__linq__1) AND ((([Extent2].[TopicId] = (CASE WHEN (@p__linq__2 = 1) THEN @p__linq__3 ELSE 0 END)) AND ( NOT ((1 = 0) OR (CASE WHEN (@p__linq__2 = 1) THEN @p__linq__3 ELSE 0 END IS NULL)))) OR (1 = 0)) AND ([Extent2].[ReceiptCount] > 1)
) AS [Project1]
) AS [Project1]
WHERE [Project1].[row_number] > 50
ORDER BY [Project1].[ReceiptId] ASC

/*
DateTime p__linq__0 = 8/20/2013 1:56:23 PM
Int32 p__linq__1 = 20
Boolean p__linq__2 = True
Int32 p__linq__3 = 4
*/
```
Comments: __EF Team Triage:__ The SQL we generate is functionally correct and there don't appear to be any major perf implications. This would just be a readability fix and it doesn't seem worth it.

Closed Feature: Consider including pre-generated mapping views for schema model in providers [1573]

$
0
0
I ran some experiments and found that pre-generated mapping views can improve start up time for things like the designer (and potentially other services that use the schema discovery model, such as a default DatabaseTableChecker implementation).

In the case of SQL Sever it only saves around half a second in my box, but if it can be significant for other databases it would be a good thing to encourage provider writers to do it.
Comments: We aren't planning to do this at this stage.

Closed Task: Update EntityFramework.Sample NuGet Package [1565]

$
0
0
We should consider taking over and updating the [EntityFramework.Sample](http://www.nuget.org/packages/EntityFramework.Sample/) NuGet package.
Comments: The package is hardly used and it doesn't seem worth the effort.

Closed Issue: Designer: We should dispose view models properly [1562]

$
0
0
We do not track and dispose view models properly and therefore may end up in a situation where we have multiple view models for a single model. This causes issues since we subscribe to some events that are later fired on view models that should actually not exist. View models implement IDisposable and disposing a view model should unsubscribe from the events a view model is subscribed to. For EF6 we just fixed the symptoms (see https://entityframework.codeplex.com/workitem/1513) but not the root cause.

Some additional comments from the review that might be helpful:
_
- Could there be a case where we had an empty view-model - we then do something to update the underlying model so it's now valid - we should reload but because the view-model is still empty we fail to do so?

- Have you checked that all the links still work on an empty model e.g. "Modify the namespaces"...

- Another example (a bit contrived admittedly) would be having the file open at watermark in VS and the user editing the file externally to VS to fix it.

1) Reloading an edmx file consists of 4 main steps:
- clearing the entity view model (i.e. removing references between the model items and the DSL items)
- clearing the diagram
- reloading the model
- recreating the diagram
so if we update the underlying model reload should recreate the diagram.

2) I did. It worked fine - I looked a little bit and in this case even though we had a watermark we actually were able to find the diagram and reloading events need to be invoked otherwise the links would not work (this case actually broke my original fix which was to skip registering the events entirely for watermarks). Note that the code search through the shapes to find the diagram (which is in the DSL layer) so it is not easy to track when the diagram is being added.

3) I tried that and it worked - after modifying the underlying edmx file I was asked if I wanted to reload the file and when I did I was able to see the model fine._

The related work item (https://entityframework.codeplex.com/workitem/1513) contains a scenario that reproduces the problem but after fixing this we need to make sure that all other scenarios where we show watermark works (EF6 on .NET Framework 4, including empty models, retargeting, update database from model), the behavior is correct when the user clicks on the links in the watermark (especially upgrading/downgrading the version of the model works).

Scenarios with EF6 in a .NET Framework 4 project which does not have any reference to EF are by the far most susceptible. This is because the default schema version on .NET Framework 4 will be v2 if the project does not have any reference to EF but when EF6 is picked in the wizard the default schema version is bumped to v3 and we need to reload the edmx file (and if the project contains other edmx file they will be v2 and will no longer match the schema version supported by the project. Note that if they were open before they will continue to be open even if they are v2 but if you close and re-open them watermark will be shown).

Other related issues:
- https://entityframework.codeplex.com/workitem/1452
- https://entityframework.codeplex.com/workitem/1266
- https://entityframework.codeplex.com/workitem/1337
Comments: __EF Team Triage:__ Pawel has looked at this and it doesn't cause any issues in the current code base. We can deal with it if it ever causes issues in the future.

Closed Feature: Designer: Ability to specify not to use IsOfType(...) in EntityTypeMapping to enable some inheritance scenarios [1527]

$
0
0
We could add UI in Mapping Details to specify whether IsOfType(_EntityType_) should be used in MSL. Currently it is always generated and that renders some inheritance scenarios impossible to resolve within the designer. We believe many cases of [error 3032](http://www.bing.com/search?q=error+3032+entity+framework) and possibly other errors are due to this limitation.

Consider the following model:

```
public abstract class Creature
{
public int Id { get; set; }
}

public abstract class Animal : Creature
{
public bool IsCute { get; set; }
}

public class Herbivore : Animal
{
public string FavoritePlant { get; set; }
}

public class Carnivore : Animal
{
public string FavoriteAnimal { get; set; }
}

public class Human : Creature
{
public string Name { get; set; }
}

public class MyContext : DbContext
{
public DbSet<Creature> Creatures { get; set; }
}
```

It is not possible to create this in the designer (__abstract__ class Animal and __concrete__ class Human inheriting from class Creature).

The designer reports the following error:

Error 3032: Problem in mapping fragments starting at lines 54, 80:EntityTypes YADB.Carnivore, YADB.Herbivore, YADB.Human are being mapped to the same rows in table Creatures. Mapping conditions can be used to distinguish the rows that these types are mapped to.

Msl fragment in question looks like this:

```
<EntitySetMapping Name="Creatures">
<EntityTypeMapping TypeName="IsTypeOf(YADB.MyContextModel.Creature)">
<MappingFragment StoreEntitySet="Creatures">
<ScalarProperty Name="Id" ColumnName="Id" />
</MappingFragment>
</EntityTypeMapping>
<EntityTypeMapping TypeName="IsTypeOf(YADB.MyContextModel.Carnivore)">
<MappingFragment StoreEntitySet="Creatures">
<ScalarProperty Name="Id" ColumnName="Id" />
<ScalarProperty Name="FavoriteAnimal" ColumnName="FavoriteAnimal" />
<Condition ColumnName="Discriminator" Value="Carnivore" />
</MappingFragment>
</EntityTypeMapping>
<EntityTypeMapping TypeName="IsTypeOf(YADB.MyContextModel.Herbivore)">
<MappingFragment StoreEntitySet="Creatures">
<ScalarProperty Name="Id" ColumnName="Id" />
<ScalarProperty Name="FavoritePlant" ColumnName="FavoritePlant" />
<Condition ColumnName="Discriminator" Value="Herbivore" />
</MappingFragment>
</EntityTypeMapping>
<EntityTypeMapping TypeName="IsTypeOf(YADB.MyContextModel.Human)">
<MappingFragment StoreEntitySet="Creatures">
<ScalarProperty Name="Id" ColumnName="Id" />
<ScalarProperty Name="Name" ColumnName="Name" />
<Condition ColumnName="Discriminator" Value="Human" />
</MappingFragment>
</EntityTypeMapping>
<EntityTypeMapping TypeName="IsTypeOf(YADB.MyContextModel.Animal)">
<MappingFragment StoreEntitySet="Creatures">
<ScalarProperty Name="Id" ColumnName="Id" />
<ScalarProperty Name="IsCute" ColumnName="IsCute" />
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>
```

There is no problem with this structure, if one uses CodeFirst. Msl in that case looks as follows:

```
<EntitySetMapping Name="Creatures">
<EntityTypeMapping TypeName="YADB.Carnivore">
<MappingFragment StoreEntitySet="Creature">
<ScalarProperty Name="Id" ColumnName="Id" />
<ScalarProperty Name="IsCute" ColumnName="IsCute" />
<ScalarProperty Name="FavoriteAnimal" ColumnName="FavoriteAnimal" />
<Condition Value="Carnivore" ColumnName="Discriminator" />
</MappingFragment>
</EntityTypeMapping>
<EntityTypeMapping TypeName="YADB.Herbivore">
<MappingFragment StoreEntitySet="Creature">
<ScalarProperty Name="Id" ColumnName="Id" />
<ScalarProperty Name="IsCute" ColumnName="IsCute" />
<ScalarProperty Name="FavoritePlant" ColumnName="FavoritePlant" />
<Condition Value="Herbivore" ColumnName="Discriminator" />
</MappingFragment>
</EntityTypeMapping>
<EntityTypeMapping TypeName="YADB.Human">
<MappingFragment StoreEntitySet="Creature">
<ScalarProperty Name="Id" ColumnName="Id" />
<ScalarProperty Name="Name" ColumnName="Name" />
<Condition Value="Human" ColumnName="Discriminator" />
</MappingFragment>
</EntityTypeMapping>
<EntityTypeMapping TypeName="IsTypeOf(YADB.Creature)">
<MappingFragment StoreEntitySet="Creature">
<ScalarProperty Name="Id" ColumnName="Id" />
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>

```

We should make a designer to generate a similar thing, to enable these scenarios.




Comments: __EF Team Triage:__ Seems very low priority and not worth the effort.

Commented Unassigned: getting "entity types cannot share table" for same-named tables in different schemas [1641]

$
0
0
I pulled CF DbContext classes recently created from EF PowerTools 0.7.0.0 in a VS2012/EF 5.0.0 project into a brand new EF 6.0.0-rc1 project. The app worked fine in EF 5.0.0. Now when I attempt to use the DbContext in EF 6.0.0-rc1 I get the "entity types cannot share table" error (even though the fluent configuration for the classes specify the correct ToTable mappings).
Comments: I tried the above repro on EF5 and EF6 beta1 and I see the same exception on both however both customers said it worked before so it must be slightly different scenario.

Closed Issue: Consider providing better error message when installing tooling with no VS on the machine [1520]

$
0
0
If you attempt to install the tooling on a machine with the wrong version of VS installed, or no VS, then the error message is:

Visual Studio product directory is not found


Comments: __EF Team Triage:__ Low priority and not worth the effort.

Closed Task: Consider using runtime utilities in tooling [1511]

$
0
0
Consider copying some of the runtime's general-purpose extension methods and utility classes to the designer (e.g. String.EqualsIgnoreCase)
Comments: __EF Team Triage:__ We can just do this lazily on an as-needed basis.

Closed Feature: Designer: Map Many-Many association into a stored procedure [1504]

$
0
0
It should be possible to map Many-Many association into stored procedure (we do that using code first, for instance). However, there is no way to do that at the moment using a EF Designer.
Comments: __EF Team Triage:__ We haven't seen anyone ask for this - this issue was opened by a member of the EF team. If we get requests in the future we can consider it.

Closed Issue: Designer: Investigate not checking out files when not needed [1493]

$
0
0
From a bug bash...

I see that immediately after I have completed checkin my project these files always appear as checked out.
1. Create a model
1. Check-in all the file
1. Don't do anything

__Actual:__
Few files are always checked out.
There is no diff for the files.

This was confusing on the first go, where I felt I have not checked in everything correctly and started trying to check them in again.

Does the designer keeps these files checkout?

Ah, as soon as I close the designer, the checkout has been undone.


__Expected:__
Designer should checkout the files only when some changes are been made

Comments: __EF Team Triage:__ We haven't seen anyone ask for this - this issue was opened by a member of the EF team. If we get requests in the future we can consider it.

Commented Unassigned: Naming convention of junction table in many-to-many broken [1677]

$
0
0
From [this question at StackOverflow](http://stackoverflow.com/q/18909901/861716).

When we have a model with two classes connected by a many-to-many association the default naming convention for the junction table is different in __EF6 rc1__ than in previous versions, including EF5.

For example, classes `Agent` and `AgentGroup`. The names of the junction table in Sql Server:

* EF5 (stable): `AgentGroupAgents`
* EF6 (beta): `AgentGroupAgents`
* EF6 (rc1): `AgentAgentGroups`


Comments: OK, thanks Rowan. I'll quote this in the StackOverflow post.

Edited Issue: Designer tests don't run on a machine that has both VS2012 and VS2013 installed [1505]

$
0
0
There seem to be multiple issues related to the VS host that effectively prevent the tests from running on a machine that has both versions of VS installed, regardless of whether you are doing the VS2012 or the VS2013 build.

In addition to that the wixproj for VSIDETestHost needs to be fixed to use WixExtDir variable for the path to the Wix Tools instead of reading the hardcoded registry setting.

Closed Issue: Custom key conventions are not compatible with the [Key] annotation [647]

$
0
0
Situation: there is a custom convention that identifies a property in an entity as the primary key and there exists a [Key] annotation that specifies a different property within that entity we receive an exception reading:
"Unable to determine composite primary key ordering for type 'ConflictingLightweightConventions.Post'. Use the ColumnAttribute or the HasKey method to specify an order for composite primary keys."

this happens even if they convention specifies a index for the added key i.e. (c => c.IsKey(2))
we need to define a way for the key annotation to be compatible with key conventions
Comments: The original issue is fixed. The issue in the comment is a duplicate of this issue: https://entityframework.codeplex.com/workitem/1635

Commented Unassigned: getting "entity types cannot share table" for same-named tables in different schemas [1641]

$
0
0
I pulled CF DbContext classes recently created from EF PowerTools 0.7.0.0 in a VS2012/EF 5.0.0 project into a brand new EF 6.0.0-rc1 project. The app worked fine in EF 5.0.0. Now when I attempt to use the DbContext in EF 6.0.0-rc1 I get the "entity types cannot share table" error (even though the fluent configuration for the classes specify the correct ToTable mappings).
Comments: Introduced in https://entityframework.codeplex.com/SourceControl/changeset/a12d50d8edb2087d54931a654a34a32fee179367

Created Unassigned: Columns' uniqueness awareness. (Unique Indexes) [1680]

$
0
0
Several DataBases give you the possibility to create UNIQUE INDEXES, both to support Unique Constraint on it or just to ensure the uniqueness of some kind of data.

In both cases, this kind of information doesn't have a proper place into the model and this makes the DbContext unable to determine the proper order of the Insert/Update/Delete commands within the commands tree.

The reason is pretty clear to me, if within the same SaveChanges() you delete a row or you update a index column(s) value of a row and you add a brand new row with the same original index column(s) value of the updated/delete row, the order of this two commands is VERY IMPORTANT 'cause the wrong order will end with an exception from the DB!

In my previous experiences I wrote a tons of code executed during the SaveChanges() to inspect the ObjectStateManager, to detect all the changes impacting the columns covered by a Unique Index, to remove these changes from the Context, to prepare a list of ad-hoc DbCommand in order to replicate the operation just removed and, finally, after the execution of the parent SaveChanges() but within the same DbTransaction, to execute the DbCommands.
A lot of very risky code, it took several days just only for the Unit Testing!

The Feature Request is:
Give us the opportunity to put into the Model this vital information about the uniqueness of the columns (in form of metadata) and use them while the CommandTree builder decides the statement execution order.

Created Unassigned: SQL-CE provider calculates wrong Count() in EF6 RC-1 [1681]

$
0
0
Hello,

I upgraded my application form EF 5 to EF 6-RC1 and it seems that there is an issue with the Count() implemetation in the SQL-CE Provider. Below is some sample code. It works fine with EF-5.

The Count() always returns all items and don't detect that some items are still marked as deleted.
```
if (todoItem.GoogleTask != null)
{
// Remove the Googletasklist entity if this is the only item referencing to it.
int googleTaskListId = todoItem.GoogleTask.GoogleTasklistId;
var googleTaskListCount = context.GoogleTask.Count(task => task.GoogleTasklistId == googleTaskListId);

if (googleTaskListCount < 2)
{
// Ok. clean up the Google Tasks list as well!
var googleTaskList = context.GoogleTasklist.Find(googleTaskListId);
context.GoogleTasklist.Remove(googleTaskList);
}

context.GoogleTask.Remove(todoItem.GoogleTask);
}
```

New Post: Poor performance for nullable columns

$
0
0
Hi all,

This thread on stackoverflow highlights an issue I have with the SQL generation of EF6.

http://stackoverflow.com/questions/17323547/should-the-order-of-linq-query-clauses-affect-entity-framework-performance/17873031#17873031

A simple change that will have the same effect is

Common SQL constructions for handling nullable equality comparisons do have specific SQL Server query optimizer support. One (of the many) compatible SQL query forms is (as suggested from stack overflow):

(x = y) OR (x IS NULL AND y IS NULL)
The EF-generated SQL instead follows this pattern:

((x = y) AND NOT (x IS NULL OR y IS NULL)) OR (x IS NULL AND y IS NULL)


I would code this fix/change myself but I don't know where to start looking in the codebase. :-)

Closed Unassigned: Code First, Name Relationships when other properties present [1637]

$
0
0
Trying to apply a .Map to a relationship between two tables with multiple properties in the Key but with a specific name.

this.HasRequired(t => t.MobileSummary)
.WithMany(t => t.Organisation)
.Map(m => m.MapKey("FK_MobileSummary_Organisation")
.HasForeignKey(d => new { d.PartitionId, d.Organisationd })
.WillCascadeOnDelete(false);

In order to name a FK in the database rather than taking the default name which is the crazy 'FK_Warehouse.MobileSummary_Structure.Organisation_PartitionId_OrganisationId' and to be able to specify the properties that make up that key (since there are more than one) and the no cascading delete because otherwise the Json serialization blows up...

but the Map line is not allowed in combination with the other calls.
Comments: Per last comment the MapKey method is for renaming columns and not the FK relationship.

Edited Unassigned: SQL-CE provider calculates wrong Count() in EF6 RC-1 [1681]

$
0
0
Hello,

I upgraded my application form EF 5 to EF 6-RC1 and it seems that there is an issue with the Count() implemetation in the SQL-CE Provider. Below is some sample code. It works fine with EF-5.

The Count() always returns all items and don't detect that some items are still marked as deleted.
```
if (todoItem.GoogleTask != null)
{
// Remove the Googletasklist entity if this is the only item referencing to it.
int googleTaskListId = todoItem.GoogleTask.GoogleTasklistId;
var googleTaskListCount = context.GoogleTask.Count(task => task.GoogleTasklistId == googleTaskListId);

if (googleTaskListCount < 2)
{
// Ok. clean up the Google Tasks list as well!
var googleTaskList = context.GoogleTasklist.Find(googleTaskListId);
context.GoogleTasklist.Remove(googleTaskList);
}

context.GoogleTask.Remove(todoItem.GoogleTask);
}
```

Commented Unassigned: Issue with entity configurations, varchars and IsRequired whilst using stored procedures [1619]

$
0
0
Hi,

I have experienced an issue with entity configurations whilst specifying MapToStoredProcedures.

If I use IsRequired on an string/nvarchar field, I get a validation error whilst seeding my database via an initialiser. The error states that the field is required and must be passed a value.

There appears to be no issues with any other data types.

Has anyone else experienced this?

Please see my configuration below.

Thanks,
John

```
public ExchangeRateConfiguration()
{
this.ToTable("admin.ExchangeRate");

// Properties
this.HasKey(e => e.Id);

this.Property(e => e.Id)
.HasColumnName("ExchangeRateId")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

this.Property(e => e.Rate)
.IsRequired();

this.Property(e => e.StartWeek)
//.IsRequired() This doesn't seem to work with EF code first stored procs on varchar fields...
.HasMaxLength(6);

this.Property(e => e.EndWeek)
.IsOptional()
.HasMaxLength(6);

// Relationships
this.HasRequired(e => e.Currency)
.WithMany(c => c.ExchangeRates)
.HasForeignKey(e => e.CurrencyId);

// Stored Procs
this.MapToStoredProcedures(s => s
.Insert(i => i
.HasName("usp_ExchangeRate_Insert")
.Parameter(e => e.Rate, "Rate")
.Parameter(e => e.StartWeek, "StartWeek")
.Parameter(e => e.EndWeek, "EndWeek")
.Parameter(e => e.CurrencyId, "CurrencyId"))
.Update(u => u
.HasName("usp_ExchangeRate_Update")
.Parameter(e => e.Id, "ExchangeRateId")
.Parameter(e => e.Rate, "Rate")
.Parameter(e => e.StartWeek, "StartWeek")
.Parameter(e => e.EndWeek, "EndWeek")
.Parameter(e => e.CurrencyId, "CurrencyId"))
.Delete(d => d
.HasName("usp_ExchangeRate_Delete")
.Parameter(e => e.Id, "ExchangeRateId"))
);
}
```
Comments: HI John, I'm not able to reproduce this issue. Below is a complete code listing for a console application that is based on the code you supplied and saves successfully via sprocs in an initializer. I did notice that the end of your initializer code calls Commit and Attach<T> which are not EF methods, so perhaps there is something in this custom layer that is causing an ExchangeRate with a null StartWeek to be added to the context. If you are able to provide a code listing or project that demonstrated the issue then we can look into it further. Thanks, Rowan ``` using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Repro { class Program { static void Main(string[] args) { Database.SetInitializer<MyContext>(new MyInitializer()); using (var db = new MyContext()) { foreach (var item in db.ExchangeRates.Include(e => e.Currency)) { Console.WriteLine( "{0} - {1} ({2} thru {3})", item.Currency.Name, item.Rate, item.StartWeek, item.EndWeek); } } } } public class MyContext : DbContext { public DbSet<Currency> Currencies { get; set; } public DbSet<ExchangeRate> ExchangeRates { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Configurations.Add(new ExchangeRateConfiguration()); } } public class MyInitializer : DropCreateDatabaseAlways<MyContext> { protected override void Seed(MyContext context) { context.Database.Log = Console.Write; // Create currencies var currency1 = new Currency() { Name = "Gold Deblumes", ExchangeRates = new List<ExchangeRate>() { new ExchangeRate() { Rate = 1.55, StartWeek = "200801", EndWeek = "201201" }, new ExchangeRate() { Rate = 1.65, StartWeek = "201202", EndWeek = "201212" }, new ExchangeRate() { Rate = 1.75, StartWeek = "201301" } } }; // Save things to DB context.Currencies.Add(currency1); context.SaveChanges(); } } public class Currency { public int CurrencyId { get; set; } public string Name { get; set; } public List<ExchangeRate> ExchangeRates { get; set; } } public class ExchangeRate { public int Id { get; set; } public double Rate { get; set; } public string StartWeek { get; set; } public string EndWeek { get; set; } public Currency Currency { get; set; } public int CurrencyId { get; set; } } public class ExchangeRateConfiguration : EntityTypeConfiguration<ExchangeRate> { public ExchangeRateConfiguration() { this.ToTable("admin.ExchangeRate"); // Properties this.HasKey(e => e.Id); this.Property(e => e.Id) .HasColumnName("ExchangeRateId") .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); this.Property(e => e.Rate) .IsRequired(); this.Property(e => e.StartWeek) .IsRequired() // This doesn't seem to work with EF code first stored procs on varchar fields... .HasMaxLength(6); this.Property(e => e.EndWeek) .IsOptional() .HasMaxLength(6); // Relationships this.HasRequired(e => e.Currency) .WithMany(c => c.ExchangeRates) .HasForeignKey(e => e.CurrencyId); // Stored Procs this.MapToStoredProcedures(s => s .Insert(i => i .HasName("usp_ExchangeRate_Insert") .Parameter(e => e.Rate, "Rate") .Parameter(e => e.StartWeek, "StartWeek") .Parameter(e => e.EndWeek, "EndWeek") .Parameter(e => e.CurrencyId, "CurrencyId")) .Update(u => u .HasName("usp_ExchangeRate_Update") .Parameter(e => e.Id, "ExchangeRateId") .Parameter(e => e.Rate, "Rate") .Parameter(e => e.StartWeek, "StartWeek") .Parameter(e => e.EndWeek, "EndWeek") .Parameter(e => e.CurrencyId, "CurrencyId")) .Delete(d => d .HasName("usp_ExchangeRate_Delete") .Parameter(e => e.Id, "ExchangeRateId")) ); } } } ```
Viewing all 10318 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>