我正在尝试手动执行我的linq 2 sql对象,所以我有以下代码:
var mapping = XmlMappingSource.FromXml(xml);
using (DataContext ctx = new DataContext(conn_string, mapping))
{
list = ctx.GetTable<Achievement>().ToList();
}
,XML看起来像这样:
<?xml version="1.0" encoding="utf-8" ?>
<Database Name="FatFights" xmlns="http://schemas.microsoft.com/linqtosql/mapping/2007">
<Table Name="dbo.Achievements">
<Type Name="FatFights.Business.Objects.Achievement">
<Column Name="Id" Member="Id" DbType="UniqueIdentifier NOT NULL" IsPrimaryKey="true" />
<Column Name="UserId" Member="UserId" />
<Column Name="Achieved" Member="Achieved" />
<Column Name="AchievementId" Member="AchievementTypeId" />
<Association Name="AchievementType_Achievement" Member="AchievementTypeId" ThisKey="Id" OtherKey="Id" IsForeignKey="true" />
</Type>
</Table>
</Database>
这会返回以下错误:
System.InvalidOperationException:无法在“Int32”类型上找到键'Id'的关键成员'Id'。密钥可能有误或'Int32'上的字段或属性已更改名称..
所以我需要弄清楚如何告诉Linq 2 SQL Id是GUID而不是Int32 ...所以我生成了一些Linq2SQL XML来看看它们是如何做的并且它们传递Type,但是Type不是有效的根据XSD属性,因此失败。
这是SQL表:
CREATE TABLE Achievements
(
Id UNIQUEIDENTIFIER NOT NULL CONSTRAINT RG_Achievements ROWGUIDCOL
CONSTRAINT DF_Achievements_Id DEFAULT (NEWID()),
UserId UNIQUEIDENTIFIER NOT NULL,
AchievementId INTEGER NOT NULL,
Achieved DATETIME NOT NULL,
CONSTRAINT FK_Achievements_Users
FOREIGN KEY (UserId)
REFERENCES aspnet_Users (UserId),
CONSTRAINT FK_Achievements_AcheivementTypes
FOREIGN KEY (AchievementId)
REFERENCES AchievementTypes (Id),
CONSTRAINT PK_Achievements
PRIMARY KEY (Id),
CONSTRAINT UQ_Achievements_1
UNIQUE (UserId, AchievementId)
)
和业务对象:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FatFights.Business.Objects
{
public class Achievement
{
public Guid Id { get; set; }
public Guid UserId { get; set; }
public int AchievementTypeId { get; set; }
public DateTime Achieved { get; set; }
}
}
答案 0 :(得分:1)
我怀疑问题出现在这里:
会员= “AchievementTypeId”
对于关联,您应该链接一个类型化的成员 - 例如,您可能有一个名为“AchievementType”的属性(类型为AchievementType),并且具有Member =“AchievementType”。
例如,在Northwind中,链接客户和订单显示(对于订单):
<Association Name="Customer_Order" Member="Customer"
ThisKey="CustomerID" OtherKey="CustomerID"
Type="Customer" IsForeignKey="true" />
然后,SqlMetal生成的代码有一些过于复杂的代码链接CustomerID和Customer属性。