标签: entity-framework-5

实体框架v5发布候选者在模型中使用枚举时抛出异常

按照这里的公告使用最新的EF v5候选版本.我的模型是通过EntityTypeConfiguration使用映射文件...

当我尝试用枚举(drop + recreate db)替换模型上的字符串属性时,我得到了这个异常:

System.NotSupportedException was unhandled by user code
  Message=The enum or spatial property 'Category' on type 'Vehicle' cannot be mapped. Use DbModelBuilderVersion 'V5_0' or later to map enum or spatial properties.
  Source=EntityFramework
  StackTrace:
       at System.Data.Entity.ModelConfiguration.Mappers.PropertyFilter.ValidatePropertiesForModelVersion(Type type, IEnumerable`1 explicitlyMappedProperties)
       at System.Data.Entity.ModelConfiguration.Mappers.PropertyFilter.GetProperties(Type type, Boolean declaredOnly, IEnumerable`1 explicitlyMappedProperties, IEnumerable`1 knownTypes)
       at System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.MapStructuralElements[TStructuralTypeConfiguration](Type type, ICollection`1 annotations, Action`2 propertyMappingAction, Boolean mapDeclaredPropertiesOnly, Func`1 structuralTypeConfiguration)
       at System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.MapEntityType(Type type)
       at System.Data.Entity.DbModelBuilder.<>c__DisplayClass7.<MapTypes>b__1(Type type)
       at System.Linq.Enumerable.WhereListIterator`1.MoveNext()
       at System.Data.Entity.ModelConfiguration.Utilities.IEnumerableExtensions.Each[T](IEnumerable`1 ts, Action`1 action)
       at System.Data.Entity.DbModelBuilder.MapTypes(EdmModel model) …
Run Code Online (Sandbox Code Playgroud)

c# entity-framework exception entity-framework-5

4
推荐指数
1
解决办法
3703
查看次数

多个DbContext类使用相同的连接字符串?

例如,我有以下DbContext类。

public class AppDbContext : DbContext {
    ...
}
public class LogDbContext : DbContext {
    ...
}
public class FooDbContext : DbContext {
    ...
}
Run Code Online (Sandbox Code Playgroud)

如果名为的连接字符串AppDbContext位于上,App.Config并且我希望其他DbContext类共享与该字符串相同的连接字符串AppDbContext,我可以只将字符串“ AppDbContext”用作ctorof LogDbContext和的参数FooDbContext。例如,

public class FooDbContext : DbContext {
    public FooDbContext : base("AppDbContext") { }
}
Run Code Online (Sandbox Code Playgroud)

有副作用吗?

更新2013/1/9

在尝试了@ ShinH2S的建议和一些东西之后,我放弃了这种方式,并决定给出具有不同的connectionStrings和数据库的不同的Dbcontext派生类。我已经尝试了一个测试项目,并将其放在GitHub上。当entityframework检测到由于AppDbContextFooDbContext模式具有不同的模式而导致数据库方案更改时,它将引发运行时异常。如果我DropCreateDatabaseIfModelChanges对两个DbContext派生类都分配了策略,则其中一个模型将被删除,因为模型彼此不同。

更新2017/10

这是一个老问题。在我的内存中,EF6 and above versions同一迁移表中的多个上下文可以具有不同的迁移历史记录。我更喜欢SO的答案。我大约两年没有使用C#进行编码。

entity-framework entity-framework-5

4
推荐指数
1
解决办法
1587
查看次数

实体框架延迟加载的私有支持字段

我正在使用启用了延迟加载的Entity Framework 5.我有以下代码:

    private ICollection<Subscription> _subscriptions = new Collection<Subscription>();

    public virtual ICollection<Subscription> Subscriptions
    {
        get { return _subscriptions; }
        set { _subscriptions = value; }
    }
Run Code Online (Sandbox Code Playgroud)

但这有意义吗?我想确保公共属性Subscriptions永远不为null.由于虚拟实体框架会覆盖getter和setter以提供延迟加载功能.

我是否需要此字段,或者我可以只使用自动属性,如果没有订阅,我会得到一个空列表?

c# lazy-loading entity-framework-5

4
推荐指数
1
解决办法
2178
查看次数

代码首先创建表

我正在学习教程,并尝试在userprofile表中添加一些新列.我试图创建一个新表.

 public class UsersContext : DbContext
{
    public UsersContext()
        : base("DefaultConnection")
    {
    }

    public DbSet<UserProfile> UserProfiles { get; set; }
    public DbSet<TestTabel> TestTabel { get; set; }
}

[Table("UserProfile")]
public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
    public string Mobile { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

[Table("TestTabel")]
public class TestTabel
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc-4 ef-migrations entity-framework-5

4
推荐指数
1
解决办法
2万
查看次数

如何为Entity Framework Code First项目设置新数据库

我有一个Code First Entity Framework项目.它利用我的本地./SQLEXPRESS实例进行数据库连接.

我需要将我的数据库移动到生产服务器.要将Entity Framework指向不同的SQL Server实例和不同的数据库,我需要做什么?

c# entity-framework-5

4
推荐指数
1
解决办法
617
查看次数

代码优先迁移 - Update-database -script命令生成的SQL脚本无法正常工作

我必须通过Entity Framework 5使用以下模型创建数据库:

public class Post
{
        public int PostId { get; set; }
        [MaxLength(200)]
        public string Title { get; set; }
        public string Content { get; set; }

        public int BlogId { get; set; }
        public Blog Blog { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后我添加了新的属性 Post

public string Abstract { get; set; }
Run Code Online (Sandbox Code Playgroud)

然后我跑了

Add-Migration AddPostAbstract
Run Code Online (Sandbox Code Playgroud)

在我的Migrations文件夹中创建了以下类,之后我通过添加一个SQL语句修改了这个文件

//201308300714477_AddPostAbstract.cs
public override void Up()
{
                AddColumn("dbo.Posts", "Abstract", c => c.String());
                Sql("UPDATE dbo.Posts SET Abstract = LEFT(Content, 100) WHERE Abstract IS …
Run Code Online (Sandbox Code Playgroud)

entity-framework ef-migrations entity-framework-5

4
推荐指数
1
解决办法
8732
查看次数

查询实体会在枚举字段上引发"无效操作异常"

我只是尝试了实体框架5和kendo ui的一些功能.我有以下ProductType枚举

public enum ProductType {
    [Description("Hazardous")]
    Hazardous,
    [Description("Non Hazardous")]
    NonHazardous
}
Run Code Online (Sandbox Code Playgroud)

此枚举类型是产品实体中的字段之一.

[Table("Products")]
public class Product {
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    //Other Fields ...

    [Required(ErrorMessage="Product Type is Required")]
    public ProductType ProductType {get;set;}

}
Run Code Online (Sandbox Code Playgroud)

基础SQL Server数据库中的ProductType列定义为(tinyint,not null).

我在MVC的以下控制器操作中访问产品列表

    public ActionResult _ProductList(int pageSize, int skip) {
        using (WorkUnit workUnit = new WorkUnit()) {
            IQueryable<Product> products = workUnit.ProductRepository.GetAllProducts()
                                                   .Include(p => p.Category);
            int total = products.Count();
            List<Product> productList = products.ToList<Product>(); //Throws InvalidOperationException …
Run Code Online (Sandbox Code Playgroud)

entity-framework ef-code-first entity-framework-5

4
推荐指数
1
解决办法
2980
查看次数

实体框架中的FirstOrDefault调用已缓存但数据库已更改

我有一个奇怪的问题,我以前没有经历过.我使用Entity Framework来检索我的记录.

我有以下电话:

 var dbOrganisation = repository.DbOrganisation.FirstOrDefault(c => c.Id == id);
Run Code Online (Sandbox Code Playgroud)

我希望没有缓存这个电话.因此,当我进行此调用时,我希望它可以查询数据库并检索最新的DbOrganisation对象.但事实并非如此.

我在彼此之后相对较短的时间(约5-10秒)将这种方法称为相对两次.但在此期间,此表中的十进制值可由某些第三方更改.

但是,即使值更改,FirstOrDefault调用也会检索未更新的版本.

示例情况:

  1. FirstOrDefault打电话,看到字段的十进制值Credits是50
  2. 第三方更改Credits为45
  3. FirstOrDefault拨打电话10秒钟,但是DbOrganisation仍然有50个积分

我究竟做错了什么?我以为FirstOrDefault默认情况下没有缓存调用?

sql caching entity-framework entity-framework-5

4
推荐指数
1
解决办法
2781
查看次数

Log4net与Entity Framework 5和MVC4

所以我开始这个新项目,并希望使用Log4net登录数据库.我正在使用EF进行其他事情并且连接正常.出于某种原因,L4N没有记录任何内容,但没有抛出任何错误.只是想知道我可能缺少哪些步骤,希望有人可以指出.我需要以某种方式"保存"到数据库吗?Thanx提前这么多.

我的web.config:

<log4net> 
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
  <bufferSize value="100" />
  <connectionType value="System.Data.EntityClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  <connectionString value="data source=myserver;initial catalog=Reporting;integrated security=false;persist security info=True;User ID=myid;Password=mypassword" />
  <commandText value="INSERT INTO [myschema].[Log] ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" />
  <parameter>
    <parameterName value="@log_date" />
    <dbType value="DateTime" />
    <layout type="log4net.Layout.RawTimeStampLayout" />
  </parameter>
  <parameter>
    <parameterName value="@thread" />
    <dbType value="String" />
    <size value="255" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%thread" />
    </layout>
  </parameter>
  <parameter>
    <parameterName value="@log_level" />
    <dbType value="String" />
    <size value="50" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%level" …
Run Code Online (Sandbox Code Playgroud)

c# log4net entity-framework asp.net-mvc-4 entity-framework-5

4
推荐指数
1
解决办法
7644
查看次数

使用asp.net mvc 4 + Entity Framework将图像保存到数据库

我有这个:

模型:

 public string Picture { get; set; }

 [Column(TypeName = "image")]
 public byte[] Image { get; set; }

 [Display(Name = "Display profile Image")]
 public bool DisplayItem { get; set; }
Run Code Online (Sandbox Code Playgroud)

视图:

<div class="editor-label">
    @Html.LabelFor(model => model.DisplayItem)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.DisplayItem)
    @Html.ValidationMessageFor(model => model.DisplayItem)
</div>
<div class="editor-label">
    @Html.LabelFor(m => m.Image)
</div>

<input type="file" name="file"/>
Run Code Online (Sandbox Code Playgroud)

和控制器:

public ActionResult Edit(string UserId)
{
        string username = User.Identity.Name;
        // Fetch the userprofile
        UserProfile user = db.userProfiles.FirstOrDefault(u => u.UserName.Equals(username));
        // Construct the viewmodel …
Run Code Online (Sandbox Code Playgroud)

c# database entity-framework-5 visual-studio-2012

4
推荐指数
1
解决办法
3万
查看次数