我有以下从 IdentityUser 派生的类。Person 类存储在数据库的 AspNetUsers 表中,并且在数据库端一切看起来都很好。
public class Person : IdentityUser
{
[Required]
[StringLength(50, ErrorMessage = "First name cannot be longer than 50 characters.")]
public string FirstName { get; set; }
[Required]
[StringLength(150, ErrorMessage = "Last name cannot be longer than 150 characters.")]
public string LastName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我的问题是关于创建一个具有名字和姓氏的新用户(人)。我想,首先我需要这样做:
var user = new IdentityUser() { UserName = "testing" };
IdentityResult result = userManager.Create(user,"123456");
Run Code Online (Sandbox Code Playgroud)
这将向 AspNetUsers 表插入一个新行,其中名字和姓氏字段为空。然后,通过使用 LinQ,我需要更新现有记录的名字和姓氏字段。这种做法合理吗?还有其他推荐的方法吗?
c# linq entity-framework entity-framework-6 asp.net-identity
我正在使用实体框架。我想加载一个实体,对其进行编辑,然后将更改保存回数据库中。但无论我编辑的是外键属性还是简单属性,EF 都会给出以下错误:
附加“ClassX”类型的实体失败,因为同一类型的另一个实体已具有相同的主键值。如果图表中的任何实体具有冲突的键值,则在使用“附加”方法或将实体的状态设置为“未更改”或“已修改”时,可能会发生这种情况。这可能是因为某些实体是新的,尚未收到数据库生成的键值。在这种情况下,使用“添加”方法或“已添加”实体状态来跟踪图形,然后根据需要将非新实体的状态设置为“未更改”或“已修改”。
请注意,这ClassX不是我要更新的类的直接虚拟属性,而是我的类具有导航属性的其他一些类中的虚拟属性。
我读过一些 相关问题。但我真的不知道应该如何将它们应用到我自己的问题上,因为我使用的是下面发布的通用存储库。
public class GenericRepository<T> where T : class
{
private EFDbContext context = new EFDbContext();
public IEnumerable<T> GetAll()
{
return context.Set<T>();
}
public void Insert(T entity)
{
context.Set<T>().Add(entity);
context.SaveChanges();
}
public void Update(T entity)
{
context.Entry(entity).State = System.Data.Entity.EntityState.Modified;
context.SaveChanges();
}
//removed for brevity
}
Run Code Online (Sandbox Code Playgroud)
我遇到了另一个与虚拟属性相关的问题,建议我使用ViewModels对象到对象映射。
据我所知,有3个选择:
ViewModels对象到对象的映射。我不会选择这个,这真的很痛苦,因为 O2O 映射库有很多错误。reference. 但我不能这样做,因为存储库是通用的。也许我应该使用反射 API 来实现这一点?谁能解释一下为什么会出现这个问题以及解决它的最简单方法是什么?
我的实体如下所示:
public class AddPatientReportDentalChartInput : IInputDto
{
[Required]
[MaxLength(PatientReportDentalChart.TeethDesc)]
public string Image { get; set; }
[Required]
public virtual int PatientID { get; set; }
[Required]
public virtual int TeethNO { get; set; }
public string SurfaceDefault1 { get; set; }
public string SurfaceDefault2 { get; set; }
public string SurfaceDefault3 { get; set; }
public string SurfaceDefault4 { get; set; }
public string SurfaceDefault5 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我想更新的方法是:
public async Task addPatientReportDentalChart(AddPatientReportDentalChartInput input)
{
var pid = …Run Code Online (Sandbox Code Playgroud) c# entity-framework asp.net-mvc-4 entity-framework-5 entity-framework-6
我正在尝试在 linq 表达式中使用以下代码,这是我在 这个问题中找到的 ,但是如果数据库字段为空,则会失败。
public static IQueryable<T> FieldsAreEqualOrBothNullOrEmpty<T>(
this IQueryable<T> source,
Expression<Func<T, string>> member,
string value)
{
Expression body;
if (string.IsNullOrEmpty(value))
{
body = Expression.Call(typeof(string), "IsNullOrEmpty", null, member.Body);
}
else
{
body = Expression.Equal(
Expression.Call(member.Body, "ToLower", null),
Expression.Constant(value.ToLower(), typeof(string)));
}
return source.Where(Expression.Lambda<Func<T, bool>>(body, member.Parameters));
}
Run Code Online (Sandbox Code Playgroud)
在我看来,好像代码
Expression.Call(member.Body, "ToLower", null)
Run Code Online (Sandbox Code Playgroud)
是问题所在,但我不知道在这个地方用什么。
我正在使用EFCache在我的 EF 上下文中提供二级缓存。
我遇到了一个问题,我的一个实体连接到一个提供行级安全性的视图。所以这个视图根据一些参数过滤行。使用二级缓存时,所有用户都会得到相同的结果!
我正在寻找一种从缓存中排除某些实体的方法,欢迎提供任何帮助。
这是我的缓存配置:
class CacheConfiguration : DbConfiguration
{
public CacheConfiguration()
{
var transactionHandler = new CacheTransactionHandler(new InMemoryCache());
AddInterceptor(transactionHandler);
var cachingpolicy = new cachingpolicy();
Loaded +=
(sender, e) => e.ReplaceService<DbProviderServices>(
(s, _) => new CachingProviderServices(s, transactionHandler, cachingPolicy));
}
}
Run Code Online (Sandbox Code Playgroud) 如何包含在循环中?我想指定要包含在查询中的相关对象。
我有下一个功能
public IQueryable<TEntity> Include(Expression<Func<TEntity, object>>[] includes)
{
IQueryable<TEntity> result = null;
//two includes are ok:
//IQueryable<TEntity> result2 = null;
//if (includes.Count() > 1)
//{
//result2 = dbset.Include(includes[0]).Include(includes[1]);
//}
//include in loop is not ok:
foreach (var exp in includes)
{
result = dbset.Include(exp);
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
如果我取消注释注释代码,那么 result2 就可以了。但结果并不好。
奇怪的是,如果我一步一步地调试循环,在每次迭代中检查结果然后结果就可以了。但是,如果我没有一步一步地检查结果,其中包括仅用于最后一次表达的工作。
您知道为什么这不起作用以及如何解决吗?
编辑:这是修复:
result = dbset;
foreach (var exp in includes)
{
result = result.Include(exp);
}
Run Code Online (Sandbox Code Playgroud) 我一直在尝试创建 Firebird 数据库的实体数据模型,但我无法克服这个错误:

我已经安装:
DDEX 提供程序 3.0.2.0
Firebird .NET Provider 5.0.0.0(尝试使用来自 Firebird 官方网站的 .msi 安装它并手动将引用添加到项目并从 NuGet 安装它)
EntityFramework.Firebird(来自 NuGet)
这是我的 machine.config:
<system.data>
<DbProviderFactories>
<add name="FirebirdClient Data Provider" invariant="FirebirdSql.Data.FirebirdClient" description=".NET Framework Data Provider for Firebird" type="FirebirdSql.Data.FirebirdClient.FirebirdClientFactory, FirebirdSql.Data.FirebirdClient, Version=5.0.0.0, Culture=neutral, PublicKeyToken=3750abcc3150b00c"/>
</DbProviderFactories>
</system.data>
Run Code Online (Sandbox Code Playgroud)
这是我的 App.config:
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<system.data>
<DbProviderFactories>
<remove invariant="FirebirdSql.Data.FirebirdClient" />
<add name="FirebirdClient Data Provider" invariant="FirebirdSql.Data.FirebirdClient" description=".NET Framework Data Provider for Firebird" type="FirebirdSql.Data.FirebirdClient.FirebirdClientFactory, FirebirdSql.Data.FirebirdClient" />
</DbProviderFactories>
</system.data>
<entityFramework>
<providers>
<provider invariantName="FirebirdSql.Data.FirebirdClient" type="FirebirdSql.Data.EntityFramework6.FbProviderServices, …Run Code Online (Sandbox Code Playgroud) 我目前正在 asp.net 中从事 Web 服务项目。我尝试在检索数据的函数中包含子元素。
它适用于 url :
http://localhost:8080/myEntity/?$expand=myChildElement
Run Code Online (Sandbox Code Playgroud)
但我似乎无法像这样包含以下级别的子元素:
http://localhost:8080/myEntity/?$expand=myChildElement/mySubChildElement
Run Code Online (Sandbox Code Playgroud)
这是我的功能:
public virtual async Task<IHttpActionResult> GetElements(ODataQueryOptions<TEntity> queryOptions)
{
IQueryable<TPoco> query = context.Set<TPoco>();
string[] includes = null;
string includeText = queryOptions.SelectExpand != null ? queryOptions.SelectExpand.RawExpand : null;
if(! string.IsNullOrEmpty(includeText))
{
includes = queryOptions.SelectExpand.RawExpand.Split(',');
return Ok(await query.ProjectTo<TEntity>(null, includes).ToListAsync());
}
return Ok(await query.ProjectTo<TEntity>().ToListAsync());
}
Run Code Online (Sandbox Code Playgroud)
这是我的 TPoco 模型的示例(myChildElement 可以是实体“Project”,而 mySubChildElement 可以是子实体“ProjectType”):
public class ContractEntity : BaseEntity
{
public ContractEntity()
{
this.Addresses = new HashSet<AddressEntity>();
}
override public Guid Id { get; set; } …Run Code Online (Sandbox Code Playgroud) 如何使用允许SignalR将更新从推SQLServer DB送到浏览器EF6。
这是我的操作方法:
public ActionResult Index()
{
var currentGates = _ctx.Transactions
.GroupBy(item => item.SubGateId)
.SelectMany(group => group.OrderByDescending(x => x.TransactionDateTime)
.Take(1))
.Include(g => g.Card)
.Include(g => g.Student)
.Include(g => g.Student.Faculty)
.Include(g => g.Student.Department)
.Include(g => g.SubGate)
.ToList();
return View(currentGates);
}
Run Code Online (Sandbox Code Playgroud)
经过大量搜索,我得到的唯一结果是:
ASP.NET MVC 5 SignalR,SqlDependency和EntityFramework 6
我尝试了建议的方法,但是它没有用,此外,我发现了一个非常重要的安全问题,涉及在隐藏字段中存储敏感数据!
我的问题是:
如何根据
Insert交易表中的任何内容更新我的视图?
我正在开发一个 MVC 4 项目,该项目使用 EF 6 进行与数据库 (SQL Server) 之间的所有操作。我必须进行一些重构才能使用更明确的 Fluent API。基本上,现在项目中的每个实体都有其对应的所有映射的 Fluent API 代码。
当我尝试从包管理器控制台运行 EF 命令时,问题就出现了。这是我收到的错误: 在 SqlServer 提供程序清单中找不到存储类型“Varchar(100)”
这是错误的完整日志:
PM> enable-migrations
Checking if the context targets an existing database...
System.InvalidOperationException: The store type 'Varchar(100)' could not be found in the SqlServer provider manifest
at System.Data.Entity.Utilities.DbProviderManifestExtensions.GetStoreTypeFromName(DbProviderManifest providerManifest, String name)
at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.ConfigureColumn(EdmProperty column, EntityType table, DbProviderManifest providerManifest)
at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.<>c__DisplayClass47_0.<Configure>b__0(Tuple`2 pm)
at System.Data.Entity.Utilities.IEnumerableExtensions.Each[T](IEnumerable`1 ts, Action`1 action)
at System.Data.Entity.ModelConfiguration.Configuration.Types.StructuralTypeConfiguration.ConfigurePropertyMappings(IList`1 propertyMappings, DbProviderManifest providerManifest, Boolean allowOverride)
at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.ConfigurePropertyMappings(DbDatabaseMapping databaseMapping, EntityType entityType, DbProviderManifest providerManifest, …Run Code Online (Sandbox Code Playgroud) c# sql-server asp.net-mvc entity-framework entity-framework-6
c# ×8
asp.net ×2
asp.net-mvc ×2
linq ×2
.net ×1
automapper ×1
caching ×1
firebird ×1
odata ×1
signalr ×1
sql-server ×1