简体   繁体   English

双外键:C#中的多重性错误

[英]Double foreign key: multiplicity error in C#

I have a Entity framework set of Auctions. 我有一个拍卖的实体框架集。 Every auctions has a 2 foreign key to the User DB object. 每次拍卖都有一个指向User DB对象的2个外键。 [the creator (required) and the current winner (optional)] [创建者(必填)和当前获奖者(可选)]

    ....

public class UserDB { 公共类UserDB {

    [Key]
    public int Id { get; set; }
    public virtual ICollection<AuctionDB> WinnerOfAucts { get; set; }
    public virtual ICollection<AuctionDB> SellerOfAucts { get; set; }

... } public class AuctionDB { ...}公共类AuctionDB {

    [Key]
    public int Id { get; set; }
    public virtual UserDB WinnerUser { get; set; }
    public virtual int WinnerUserId { get; set; }
    public virtual int SellerId { get; set; }  
    public virtual UserDB Seller { get; set; }

... } ...}

There is the code of the foreign keys: 有外键的代码:

modelBuilder.Entity<AuctionDB>().HasRequired(a => a.Seller).WithMany(u => u.SellerOfAucts).HasForeignKey(a => a.SellerId).WillCascadeOnDelete(true);
            modelBuilder.Entity<AuctionDB>().HasOptional(a => a.WinnerUser).WithMany(u => u.WinnerOfAucts).HasForeignKey(a => a.WinnerUserId).WillCascadeOnDelete(false);

The project keeps saying this error message: SetUp: System.Data.Entity.ModelCongifuration.ModelValidationException : One or more validation errors were detected during model generation: 项目一直说此错误消息:SetUp:System.Data.Entity.ModelCongifuration.ModelValidationException:在模型生成期间检测到一个或多个验证错误:

AuctionSite.AuctionDB_WinnerUser: : Multitplicity conflicts with the referential constraint in Role 'AuctionDB_WinnerUser_Target' in relationship 'AuctionDB_WinnerUser'. AuctionSite.AuctionDB_WinnerUser::多重性与关系“ AuctionDB_WinnerUser”中角色“ AuctionDB_WinnerUser_Target”中的引用约束冲突。 Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'. 因为从属角色中的所有属性都是不可为空的,所以主体角色的多重性必须为'1'。

The problem is on the db.Database.Delete() method: 问题出在db.Database.Delete()方法上:

            if (connectionString == null) throw new ArgumentNullException();
        using (var db = new AuctionContext(connectionString))
        {
            try
            {
                db.Database.Delete();
                db.Database.Create();
            }
            catch (SqlException)
            {
            throw new UnavailableDbException();}

Any help? 有什么帮助吗? Thank you 谢谢

Initialise your collection 初始化您的收藏

public UserDB()
{
WinnerOfAucts = new List<AuctionDB>();
SellerOfAucts = new List<AuctionDB>();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM