鉴于以下POCO课程:
public class Certification {
public int Id { get; set; }
public virtual ICollection<Employee> CertifiedEmployees { get; set; }
}
public class Employee {
public int Id { get; set; }
public virtual ICollection<Certification> Certifications { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
使用EF4 CTP4代码第一种方法创建数据库模型会创建所需的联结表:
CREATE TABLE [dbo].[Certifications_CertifiedEmployees](
[Certifications_Id] [int] NOT NULL,
[CertifiedEmployees_Id] [int] NOT NULL,
...
Run Code Online (Sandbox Code Playgroud)
但是,表名和列名称并不理想,因为它们是从关联的类属性名称生成的.我宁愿:
CREATE TABLE [dbo].[Employees_Certifications](
[Employee_Id] [int] NOT NULL,
[Certification_Id] [int] NOT NULL,
...
Run Code Online (Sandbox Code Playgroud)
有谁知道在这种情况下是否可以更改生成的列名称,还可以选择更改表名,以便Employees在Certifications之前?
谢谢,加里
我正在尝试运行以下代码,但是通过不将我期望的实体交给我,比较失败了.
它比较06/09/2011 0:00:00到06/09/2011 12:25:00,后者是我的数据库记录值.这就是比较失败的原因,我没有得到我需要的记录.
我只是想比较日期是否匹配,我不关心时间.
DateTime today = DateTime.Now.Date;
var newAuctionsResults = repo.FindAllAuctions()
.Where(a => a.IsActive == true || a.StartTime.Value == today)
.ToList();
Run Code Online (Sandbox Code Playgroud)
我怎样才能比较日期?
如果在.StartTime.Value部分使用.Date属性,我会得到一个异常:
LINQ to Entities不支持指定的类型成员"Date".仅支持初始值设定项,实体成员和实体导航属性.
我收到以下错误:
System.InvalidOperationException未处理Message =类型'Judge'未归因于EdmEntityTypeAttribute,但包含在使用EdmSchemaAttribute归属的程序集中.不使用EdmEntityTypeAttribute的POCO实体不能与使用EdmEntityTypeAttribute的非POCO实体包含在同一程序集中.
Source = EntityFramework StackTrace:System.Data.Entity.InternalContext.UpdateEntitySetMappingsForType(Type entityType)at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)....
public class GenericRepository<TEntity> where TEntity : class
{
internal z context;
internal DbSet<TEntity> dbSet;
public GenericRepository(z context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}
public GenericRepository()
{
this.context = new z();
this.dbSet = context.Set<TEntity>();
}
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
foreach (var …Run Code Online (Sandbox Code Playgroud) 如果是模型优先,我们使用[MetadataType(typeof(ConceptMetadataSource))]附加MetadataSource文件,其中包含所有数据注释,如 [HiddenInput(DisplayValue = false)]或[Display(Name = "Title")].
例如:
[MetadataType(typeof(ConceptMetadataSource))]
public partial class Concept
...
Run Code Online (Sandbox Code Playgroud)
现在,我使用数据库优先方法,因为有一个现有的数据库.这次,实体类由edmx模型自动创建.在每个实体类的开头,下面都有注释行:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)
由于一旦我们修改了数据库中的表,代码就会重新生成,每次重新生成实体类时都会删除数据注释.
谁能告诉我注释那些实体类的最佳方法是什么?谢谢.
entity-framework entity-framework-4 asp.net-mvc-3 database-first
我有相当简单的表格结构如下,发出的声音对我来说很奇怪.虽然我选择了解决它,但想听听专家的意见.
我有两张桌子
Users
UserName nvarchar(250) Primary Key
FirstName nvarchar(50)
LastName nvarchar(50)
Registrations
Id BigInt PrimaryKey
User nvarchar(250) - Foreign to Users Table
Date - DateTime
Data I have is as follows.
Users
UserName FirstName LastName
a Small A
b Small B
Registrations
Id User Date
1 A 1/1/12
2 B 1/1/12
Run Code Online (Sandbox Code Playgroud)
请注意这里的用户案例是它在SQL中有效,它接受.
现在是有趣的部分.我生成了EDMX,.Net 4.0,现在我执行了这段代码.
using (EFTestEntities context = new EFTestEntities())
{
var item = context.Registrations.Where(id => id.Id == 1).FirstOrDefault();
Response.Write(item.User1.LastName);
}
Run Code Online (Sandbox Code Playgroud)
它只是打破空指针异常User1抛出Null,当我将Registrations表中的UserName列的值更改为a而不是A时它可以工作.
这个链接谈论有点相似
这 …
我在代码隐藏文件中的asp.net页面上有一个代码段.我决定将它移动到模块中的公共子例程(general_functions.vb).但是,一旦我这样做了,代码就不再起作用 - 它会引发错误.
在原始的代码隐藏中,我用这样的调用替换了原始代码:
DeleteResidency(people_id, semester, year)
Run Code Online (Sandbox Code Playgroud)
现在在我的general_functions.vb中,我创建了一个公共子例程,如下所示:
Public Sub DeleteResidency(delpeople_id, delsemester, delyear)
Using dbContext as pbu_housingEntities = New pbu_housingEntities
Dim remove_selection = (From p in dbContext.Residents _
Where p.people_code_id = delpeople_id _
Where p.year = delyear _
Where p.semester = delsemester _
Order By p.id Descending _
Select p).FirstOrDefault
End Using
End Sub
Run Code Online (Sandbox Code Playgroud)
它有更多的代码,但上面的代码抛出了错误.我得到的错误是:
LINQ to Entities无法识别方法'System.Object CompareObjectEqual(System.Object,System.Object,Boolean)'方法,并且此方法无法转换为商店表达式.
任何人都可以帮助我理解为什么会这样吗?
今天我将旧的应用程序从EF 4.2迁移到EF 4.3.1.在我的应用程序中,我使用CodeFirst,但在迁移后它停止工作,并找不到原因.为了清除任何其他可能的问题,我决定创建一个小型控制台应用程序,并使用ADO团队发布的数据迁移演练:
http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-code-based-migrations-walkthrough.aspx
我完全复制了博客的代码,但是没有正确工作(创建数据库,创建模式,插入博客),我得到了一些错误:
Conversion failed when converting datetime from character string."所有这些都在SQL Server 2005 Express上.
我尝试使用SQL Compact,但结果相同(不同的错误):
The format of the specified date or time datepart is not valid. [ String = 2012-04-19T13.21.04.364 ]我认为在这两种情况下,问题都在于EF希望作为第一次迁移进入的界限:
INSERT INTO [__MigrationHistory] ([MigrationId], [CreatedOn], [Model], [ProductVersion])
VALUES ('201204191321184_init', '2012-04-19T13.21.04.364', ...., '4.3.1');
Run Code Online (Sandbox Code Playgroud)
显然与格式有关.是错的,至少在我的语言环境中,它应该是:
这是一个错误还是什么?它始终与其他日期时间一起使用.
更新 我尝试将其作为显式迁移运行,并使用-verbose标志设置应用迁移,这是我得到的:
PM> Update-Database -Verbose
Using NuGet project 'ConsoleApplication2'.
Using StartUp project 'ConsoleApplication2'.
Target database is: '|DataDirectory|ConsoleApplication2.ConsoleApplication1.BlogContext.sdf' (DataSource: |DataDirectory|ConsoleApplication2.ConsoleApplication1.BlogContext.sdf, Provider: System.Data.SqlServerCe.4.0, Origin: Convention).
Applying …Run Code Online (Sandbox Code Playgroud) sql-server-ce entity-framework-4 ef-code-first ef-migrations
我有一个MVC3项目,它使用Ninject,实体框架和工作单元模式与服务层.
我的AsyncService类有一个启动后台任务的函数,作为示例,它将用户添加到用户存储库.我目前的问题是,在我收到DbContext已被处理的错误之前,任务只能正确运行几秒钟.我注入Ninject的InRequestScope()的数据库上下文似乎正在处理,因为InRequestScope()将它与HttpContext联系起来.
我已经阅读了InThreadScope(),但是我不确定如何在我的MVC项目中正确实现它.
我的问题是:在我的任务中使用Ninject的正确方法是什么?
public class AsyncService
{
private CancellationTokenSource cancellationTokenSource;
private IUnitOfWork _uow;
public AsyncService(IUnitOfWork uow)
{
_uow = uow;
}
public void AsyncStartActivity(Activity activity)
{
...snip...
this.cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = this.cancellationTokenSource.Token;
var task = Task.Factory.StartNew(() =>
{
foreach (var user in activity.UserList)
{
this._uow.UserRepository.Add(new User() {UserID = user});
}
this._uow.Save();
}, cancellationToken);
...snip...
}
}
Run Code Online (Sandbox Code Playgroud) ninject unit-of-work task-parallel-library entity-framework-4 asp.net-mvc-3
我有多个服务,每个服务都UnitOfWork使用Simple Injector IoC容器注入构造函数.
目前我可以看到每个UnitOfWork实例都是一个单独的对象,这很糟糕,因为我使用的是Entity Framework,并且需要在所有工作单元中使用相同的上下文引用.
如何确保UnitOfWork每个解析请求将相同的实例注入到所有服务中?UnitOfWor命令完成后,我将由外部命令处理程序装饰器保存.
请注意,这是一个公共库,将用于MVC和Windows Forms,如果可能的话,为两个平台提供通用解决方案会很不错.
代码如下:
// snippet of code that registers types
void RegisterTypes()
{
// register general unit of work class for use by majority of service layers
container.Register<IUnitOfWork, UnitOfWork>();
// provide a factory for singleton classes to create their own units of work
// at will
container.RegisterSingle<IUnitOfWorkFactory, UnitOfWorkFactory>();
// register logger
container.RegisterSingle<ILogger, NLogForUnitOfWork>();
// register all generic command handlers
container.RegisterManyForOpenGeneric(typeof(ICommandHandler<>),
AppDomain.CurrentDomain.GetAssemblies());
container.RegisterDecorator(typeof(ICommandHandler<>),
typeof(TransactionCommandHandlerDecorator<>));
// register …Run Code Online (Sandbox Code Playgroud) .net c# dependency-injection entity-framework-4 simple-injector
我是ASP.NET的新开发人员,这是我第一次使用Linq-to-Entities和Entity Framework。我现在的问题是关于使用最佳实践来连接实体或数据库。我知道try-catch块非常昂贵。但是,当我需要连接到数据库时,是否应该使用它们?我问这个问题是因为我有大约20个实体,并且在我的数据访问层中,对于每个这些实体我都有所有的GetData()方法。您能对此提出建议吗?
C#代码:
public static IEnumerable<Items> getData()
{
List<Items> itemsList = new List<Items>();
try
{
using (ItemsDBEntities context = new ItemsDBEntities())
{
itemsList = (from item in context.Items
select new Items()
{
ID = item.ID,
Code = item.Code,
Name = item.Name,
StatusID = item.StatusID
}).ToList();
}
}
catch (EntityException ex)
{
//something wrong about entity
}
catch (Exception ex)
{
//Don't know what happend...
}
return itemsList;
}
Run Code Online (Sandbox Code Playgroud) c# ×4
.net ×2
asp.net ×2
c#-4.0 ×1
code-first ×1
datetime ×1
linq-to-sql ×1
many-to-many ×1
ninject ×1
repository ×1
unit-of-work ×1
vb.net ×1